【发布时间】:2014-04-05 01:12:24
【问题描述】:
所以我想在文本文件的特定点写一个字符串。应该很容易,但这是我第一次使用 BufferedWriter 类。我的来源如下:
public static String readFile(String fileName) throws IOException {
String toReturn = "";
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("test.txt"));
while ((sCurrentLine = br.readLine()) != null) {
toReturn = toReturn+"\n"+sCurrentLine;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return toReturn;
}
public static void addAfter(String toAdd, char after, String fileName) throws IOException {
String file = readFile(fileName);
int length = file.length();
char[] chr = file.toCharArray();
boolean pos[] = new boolean[length];
for(int i = 0; i < length; i++) {
if(chr[i] == after) {
pos[i] = true;
}
}
BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
}
我想使用 BufferedWriter 类将 String toAdd 添加到位置 i。我将如何跳转到所需的点并写入 toAdd?
提前致谢
【问题讨论】:
-
RandomAccessFile具有跳转到文件中特定字节的方法。我认为方法是skipBytes()或类似的东西。但是,如果您尝试插入文本,这将有点棘手,因为默认情况下,文件 IO 是作为覆盖完成的。您需要做的是从那时起读取原始文件并附加它。 -
要做到这一点,我认为你必须将文件的内容读入一个字符串,用你的编辑创建一个新的字符串,然后用你的新字符串覆盖文件。见stackoverflow.com/questions/3935791/…。
-
@ktm5124 感谢您的链接,我使用了与那里描述的方法类似的方法
标签: java file text bufferedreader bufferedwriter