我编写了java代码来从具有200k记录的文件中删除初始字符,该文件正在删除初始字符,但它会逐行读取文件并删除字符。程序执行速度非常慢。可以对下面的代码进行任何调整以更快地执行它吗?
程序正在执行并将输出写入文件,但速度非常慢
import java.io.*;
import java.util.Scanner;
public class truncate {
public static void main(String [] args) {
// The name of the file to open.
String inputfile = "C:\\Program Files\\eclipse\\twfiles.txt";
String outputfile = "C:\\Program Files\\eclipse\\rename.txt";
// This will reference one line at a time
String line = "";
int number_of_char_to_erased =19;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(inputfile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
File input = new File(inputfile);
Scanner scan = new Scanner(input);
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while (scan.hasNext()) {
line = scan.nextLine();
line = line.substring(number_of_char_to_erased);
print.println(line);
}
scan.close();
print.close();
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
inputfile + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ inputfile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
最佳答案
这里的问题似乎是您刚刚创建了一个缓冲读取器来读取文件。然后,它读取文件的第一行。然后,您创建一个扫描程序来读取文件中的所有行,并省略某些字符。然后 BufferedReader 读取文件中的下一行。这个过程会不断重复。所以你所要做的就是这样:
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while((line = bufferedReader.readLine()) != null) {
print.println(line.substring(number_of_char_to_erased);
}
print.close();
这应该快得多。基本上,由于您已经将行分配给从文件中读取的行,因此您可以简单地将该行打印出来(减去字符数)到输出文件。扫描仪的整个 for 循环是完全不必要的,并且关闭和打开每行的打印流也是不必要的。
编辑:删除了 println 语句,因为它会减慢速度。
关于Java代码删除文件的初始行执行速度非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26360235/