我正在尝试在现有文件的每一个第100个字符处引入一个换行符。但是它没有写任何内容。下面是用java编写的代码,用于读取现有文件并使用临时文件写入。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReplaceFileContents {
public static void main(String[] args) {
new ReplaceFileContents().replace();
}
public void replace() {
String oldFileName = "Changed1.ldif";
String tmpFileName = "Changed2.ldif";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
line.replaceAll("(.{100})", "$1\n");
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
答案 0 :(得分:7)
while ((line = br.readLine()) != null) {
line.replaceAll("(.{100})", "$1\n");
}
首先,line.replaceAll
不会用结果替换你的line变量。由于Strings
是不可变的,因此此方法返回新字符串,因此您的行应为line = line.replaceAll(...
。
其次,您永远不会将新的String
写回文件中。使用replaceAll
不会以任何方式更改文件本身。相反,请尝试使用bw
对象将新String
写入同一行。
答案 1 :(得分:1)
根据您在此处发布的内容,您永远不会尝试将line
写回bw
。试试这个:
package hello;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
new Test().replace();
}
public void replace() {
String oldFileName = "d:\\1.txt";
String tmpFileName = "d:\\2.txt";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
line = line.replaceAll("(.{100})", "$1\n");
bw.write(line);
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
bw
; String#replaceAll
将返回源的副本,而不是原始String
;