[英]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.