Writing Multiple Lines to a File (.txt) in Java
本问题已经有最佳答案,请猛点这里访问。
我不熟悉文件流,希望能得到一些帮助。以下代码是我用来写入指定文件的代码。
1 2 3 | OutputStream outStream = new FileOutputStream(file); outStream.write(contentsToWrite.getBytes()); outStream.close(); |
Java有一些包装类来实现文件流。
1 2 3 4 5 6 7 8 9 10 11 12 13 | boolean append = true; String filename ="/path/to/file"; BufferedWriter writer = new BufferedWriter(new FileWriter(filename, append)); // OR: BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename, append))); writer.write(line1); writer.newLine(); writer.write(line2); writer.newLine(); // ...... writer.close(); |
有一个好的、简单的方法,它允许您使用想要写入的字符串列表和文件本身来完成此操作。
1 2 | List<String> lines=new ArrayList<>(contentToWrite);//if it is an array or something that isn't a list Files.write(file.toPath(),lines); |
FileOutputstream类构造函数方法具有第二个参数。如果你把它设为真。它将附加您所写文件的内容。并且"
"可以更改为新行。
1 2 3 4 5 6 7 | OutputStream outStream = new FileOutputStream("a.txt",true); outStream.write("hello".getBytes()); outStream.write(" ".getBytes()); outStream.write("hello".getBytes()); outStream.close(); |