这是我读取文件和写文件的代码;我想将字符串内容写入文本文件的末尾。我的目标是在文本文件中命令光标移动/控制。
请帮助我谢谢
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Filing {
public static void main(String[] args) throws IOException
{
String content = "This is the content to write into file";
BufferedReader br =
new BufferedReader(new FileReader("C:/Users/Ashad/Desktop/text.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
FileWriter fw = new FileWriter("C:/Users/Ashad/Desktop/text.txt");
BufferedWriter bw = new BufferedWriter(fw);
while (line != null)
{
sb.append(line);
sb.append("\n");
line = br.readLine();
}
//** bw.write(content) ; **//
String everything = sb.toString();
System.out.append(everything);
}
finally
{ br.close();}
我无法在文件中已存在的文本后写入字符串内容。
答案 0 :(得分:1)
我想将字符串内容写入文本文件的末尾
然后只使用带有append
标志的overload of the FileWriter
constructor:
FileWriter fw = new FileWriter("C:/Users/Ashad/Desktop/text.txt", true);
就个人而言,我更喜欢使用FileOutputStream
和OutputStreamWriter
- 这样您就可以指定编码。
答案 1 :(得分:1)
以追加模式创建FileWriter:
FileWriter fw = new FileWriter("C:/Users/Ashad/Desktop/text.txt", true);