【问题标题】:How input Value from Scanner, and output the value to an txt file in Java?如何从 Scanner 输入值,并将值输出到 Java 中的 txt 文件?
【发布时间】:2021-07-25 04:50:37
【问题描述】:
我正在努力将 Java 中的 Scanner 选项中的值输入到 txt 文件中。虽然我可以使用 try{} catch{} 顺利读取数据,但我无法将数据从扫描仪写入 txt 文件。我可以使用 PrintWriter 轻松地将数据写入 txt 文件,但这不是我的目标......根据分配的场景,我必须创建系统来输入值并存储数据文本文件,我正在努力做到这一点.
请帮我解决这个问题,并为我提供解决方案...
这是我的第一个 Java 项目。谢谢
【问题讨论】:
标签:
javascript
java
arrays
file
command-line-interface
【解决方案1】:
正如您所说,您已成功读取(并且可能还操纵了)数据。假设您已准备好将其写为 String data,并且您还有一个字符串 filename 文件的预期名称。
然后您可以执行以下操作:
// 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();
}
【解决方案2】:
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
}