我正在测试,试图将控制台内容写入文件,但是当我运行应用程序时,生成的文本文件为空。我希望用户在输入完详细信息后输入一些详细信息。我希望用户输入文件名来写入控制台内容。但是,生成的文件为空。
public void test() {
boolean check=true;
int i=0;
for (i=0;i<5;i++) {
System.out.println("Enter your name");
String name=Keyboard.readInput();
System.out.println("Name:"+ name);
System.out.println("Enter your age");
int age=Integer.parseInt(Keyboard.readInput());
System.out.println("Age:"+age);
}
out.println("enter 1 to save to file");
int num=Integer.parseInt(Keyboard.readInput());
if (num == 1) {
out.println("Enter the file name to write to:\n");
String filename = Keyboard.readInput();
File myfile = new File(filename);
try {
PrintStream out = new PrintStream(new FileOutputStream(myfile));
System.setOut(out);
} catch (IOException e) {
out.println("Error:" + e.getMessage());
}
}
}
答案 0 :(得分:2)
您仅创建文件,而不在文件上写任何东西,这就是文件为空的原因。创建文件后,您必须通过PrintStream.println()
方法在文件上写一些东西。
try {
PrintStream out = new PrintStream(new FileOutputStream(myfile));
out.println("some text"); // it will write on File
// OR if you setOut(PrintSrtream) then
System.setOut(out);
System.out.println("some text");// this will also write on file
} catch (IOException e) {
out.println("Error:" + e.getMessage());
}
答案 1 :(得分:0)
Java 8 +
static void writeFile(String path, String...lines) throws IOException {
Files.write(
Paths.get(path),
Arrays.asList(lines));
}