Java 写入文件
在下面的示例中,我们使用 FileWriter
类及其 write()
方法将一些文本写入在上面的示例中创建的文件。请注意,当您完成对文件的写入时,应该使用 close()
方法将其关闭。
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
结果如下:
Successfully wrote to the file.