[英]Scanner only reading 1st token of a string
Java語言的新手,
以下是我的一些代碼。 但是,整個字符串不會寫入文件。 僅第一個令牌寫入文件。 有什么解釋嗎?
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FichierTexteWrite {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.println("Entrez le nom d'un fichier :");
Scanner in = new Scanner(System.in);
String filename = in.next();
FileWriter fwrite = new FileWriter(filename);
System.out.println("Entrez une phrase a memoriser");
fwrite.write(in.next());
System.out.println("Writing on file complete ");
fwrite.close();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我也嘗試過nextLine()
方法,但這似乎沒有幫助。 它強行編寫了一個空白的角色,並終止了該程序。
- -編輯 - -
我也嘗試過:
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FichierTexteWrite {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.println("Entrez le nom d'un fichier :");
Scanner in = new Scanner(System.in);
String filename = in.next();
FileWriter fwrite = new FileWriter(filename);
System.out.println("Entrez une phrase a memoriser");
fwrite.write(in.nextLine());
System.out.println("Writing on file complete ");
fwrite.close();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
如果您不相信,請編譯並運行該程序。 沒用 它不允許我輸入字符串,而是直接進入下一條指令,該指令關閉流並成功輸出文件寫入。
您應該使用in.nextLine()
來獲得整行。
fwrite.write(in.nextLine());
兩次都使用nextLine():
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FichierTexteWrite {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.println("Entrez le nom d'un fichier :");
Scanner in = new Scanner(System.in);
String filename = in.nextLine(); // *** note change
FileWriter fwrite = new FileWriter(filename);
System.out.println("Entrez une phrase a memoriser");
fwrite.write(in.nextLine());
System.out.println("Writing on file complete ");
fwrite.close();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
否則,您的nextLine()調用將讀取第一行的行尾令牌,即您在其中獲得文件名的令牌,而您不需要這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.