我编写了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();
}
}
}
答案 0 :(得分:1)
这里的问题似乎是你刚刚创建了一个缓冲读卡器来读取文件。然后,它读取文件的第一行。然后,创建一个扫描程序以读取文件中的所有行,省略某些字符。然后你的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语句,因为它会减慢它的速度。
答案 1 :(得分:0)
尝试此操作(删除扫描仪和Println,在循环外重构输出文件):
import java.io.*;
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);
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while((line = bufferedReader.readLine()) != null) {
String trimmedLine = line.substring(number_of_char_to_erased);
print.println(trimmedLine);
}
// Always close files.
bufferedReader.close();
print.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();
}
}
}