如何编辑原始文本文件并打断达到最大长度的行。JAVA
我有一个文本文件,我想通过设置每行的最大长度来组织它,然后创建一个新行。我知道我可以打开、读取和写入文件,但是我可以修复同一个文件而不必创建新文件吗 我试着编写不同的代码来实现这一点,但我仍然有一点IO API的经验,我总是遇到一个问题。到目前为止,我没有遇到任何问题:如何编辑原始文本文件并打断达到最大长度的行。JAVA,java,file,buffer,Java,File,Buffer,我有一个文本文件,我想通过设置每行的最大长度来组织它,然后创建一个新行。我知道我可以打开、读取和写入文件,但是我可以修复同一个文件而不必创建新文件吗 我试着编写不同的代码来实现这一点,但我仍然有一点IO API的经验,我总是遇到一个问题。到目前为止,我没有遇到任何问题: public static void main(String[] args) { File file = new File("data/test.txt"); BufferedReader br
public static void main(String[] args) {
File file = new File("data/test.txt");
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(file));
final int MAX_LENGTH = 80;
String line;
while((line = br.readLine()) != null) {
if(line.length() > MAX_LENGTH) {
//I want to break the line if it reached the MAX_LENGTH
//without overwriting data or skipping them
}
}
br.close();
bw.close();
} catch(IOException e) {
e.printStackTrace();
}
}
我也将感谢任何关于我的代码的建议或想法 写入文件是一个破坏性的过程,即使在可查找模式下打开文件,写入文件的某个位置也会简单地覆盖其中的内容。就个人而言,我会使用第二个文件写入更改,然后删除原始文件,并将临时文件重命名回原来的位置
File original = new File("data/test.txt");
File tmp = new File("data/temp.txt");
try {
try (BufferedReader br = new BufferedReader(new FileReader(original))) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(tmp))) {
String text = null;
while ((text = br.readLine()) != null) {
// For each line we read, we need to break the line
// down to the MAX_LENGTH and write
StringBuilder sb = new StringBuilder(text);
while (sb.length() > MAX_LENGTH) {
String line = sb.substring(0, MAX_LENGTH);
sb.delete(0, MAX_LENGTH);
bw.write(line);
bw.newLine();
}
// In case we removed all the text during the previous loop
if (sb.length() > 0) {
bw.write(sb.toString());
bw.newLine();
}
}
}
}
if (original.delete()) {
tmp.renameTo(original);
} else {
throw new IOException("Failed to remove " + original);
}
} catch (IOException exp) {
exp.printStackTrace();
}
作为一种想法将新内容写入临时文件,完成后,删除原始内容并将临时文件重命名为它的place@MadProgrammer我知道,但是不需要创建一个新文件就可以在同一个文件上写吗?不,不太可能。如果您愿意,您必须不断地向前读取,将文件的内容“向下”移动到您想要的更改范围之外,以便更容易地使用临时文件file@MadProgrammer这是真的,但当我使用临时文件时,我会做几乎相同的事情。我还是得向前读,直到那句话的那一行变得合法,你不这么认为吗?不是真的,你读了原始文件中的那一行,在新文件中添加了多少行,然后重复。它会更快