我当前的问题在于,无论我尝试用Java创建文件的哪种解决方案,都永远不会创建或显示文件。
我在StackOverflow上搜索了解决方案,并尝试了许多不同的代码,但都无济于事。我试过使用BufferedWriter,PrintWriter,FileWriter,并包装在try和catch中并抛出IOExceptions,但似乎都无法正常工作。对于需要路径的每个字段,我都尝试过单独使用文件名和路径中的文件名。什么都没有。
//I've tried so much I don't know what to show. Here is what remains in my method:
FileWriter fw = new FileWriter("testFile.txt", false);
PrintWriter output = new PrintWriter(fw);
fw.write("Hello");
只要运行过去的代码,我都不会抛出任何错误,但是,这些文件从未真正显示出来。我怎样才能解决这个问题? 预先谢谢你!
答案 0 :(得分:1)
几件事值得尝试:
1)如果您没有(显示的代码中没有此代码),请确保在处理完文件后将其关闭
2)使用文件而不是字符串。这将使您再次检查文件的创建位置
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
FileWriter fw = new FileWriter(file, false);
fw.write("Hello");
fw.close();
作为奖励,Java的try-with-resource完成后会自动关闭资源,您可能想尝试
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
try (FileWriter fw = new FileWriter(file, false)) {
fw.write("Hello");
}
答案 1 :(得分:1)
有几种方法可以做到这一点:
使用BufferedWriter进行写入:
public void writeWithBufferedWriter()
throws IOException {
String str = "Hello";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(str);
writer.close();
}
如果要附加到文件:
public void appendUsingBufferedWritter()
throws IOException {
String str = "World";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(str);
writer.close();
}
使用PrintWriter:
public void usingPrintWriteru()
throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Some String");
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
printWriter.close();
}
使用FileOutputStream:
public void usingFileOutputStream()
throws IOException {
String str = "Hello";
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = str.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
注意:
来源和更多示例:https://www.baeldung.com/java-write-to-file
希望这会有所帮助。祝你好运。