[英]How input Value from Scanner, and output the value to an txt file in Java?
I'm struggling to input value from Scanner option in Java to a txt file.我正在努力将 Java 中的 Scanner 选项中的值输入到 txt 文件中。 while I can smoothly read the data using try{} catch{}, I cannot write the data from a scanner to the txt file.
虽然我可以使用 try{} catch{} 顺利读取数据,但我无法将数据从扫描仪写入 txt 文件。 I can easily write data to txt file using PrintWriter, but that's not my goal... According to the scenario of the assignment, I have to create the system to input values and store the data text file, which I'm struggling to do.
我可以使用 PrintWriter 轻松地将数据写入 txt 文件,但这不是我的目标......根据分配的场景,我必须创建系统来输入值并存储数据文本文件,我正在努力做到这一点.
Please help me with this problem, and provide me a solution... This is my first Java project.请帮我解决这个问题,并为我提供解决方案……这是我的第一个 Java 项目。 Thanks
谢谢
Scanner sc = new Scanner(System.in);
String data = sc.nextLine(); //taking input from user
// Use try with resource to release system resources
try ( FileWriter myWriter = new FileWriter("filename.txt"); ) {
myWriter.write(data); //writing into file
}
As you say you have successfully read (and maybe also manipulated) the data.正如您所说,您已经成功读取(并且可能还操纵了)数据。 Lets assume you have it ready to be written out as a
String data
and you also have a String filename
of the file's intended name.假设您已准备好将其作为
String data
写出,并且您还具有文件预期名称的字符串filename
名。
You can then do the following:然后,您可以执行以下操作:
// generate the File object
File f = Paths.get("./" + filename).toFile();
f.delete(); // remove previous existing file -- equivalent to overwrite
try(BufferedWriter wr = new BufferedWriter(new FileWriter(f))){
wr.append(data); // adding the data into write buffer
wr.flush(); // writing the data out to the file
wr.close(); // closing the buffered writer
} catch (Exception e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.