?
要实现将文件中的特定行复制到新文件,可以按照以下步骤进行:
String inputFile = "path/to/inputFile.txt";
String outputFile = "path/to/outputFile.txt";
FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(outputFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
int[] lineNumbersToCopy = {2, 5};
String line;
int lineNumber = 1;
while ((line = bufferedReader.readLine()) != null) {
if (isLineNumberToCopy(lineNumber, lineNumbersToCopy)) {
// 复制当前行到新文件
bufferedWriter.write(line);
bufferedWriter.newLine();
}
lineNumber++;
}
boolean isLineNumberToCopy(int lineNumber, int[] lineNumbersToCopy) {
for (int number : lineNumbersToCopy) {
if (lineNumber == number) {
return true;
}
}
return false;
}
bufferedReader.close();
bufferedWriter.close();
完整代码示例:
import java.io.*;
public class FileLineCopier {
public static void main(String[] args) {
String inputFile = "path/to/inputFile.txt";
String outputFile = "path/to/outputFile.txt";
int[] lineNumbersToCopy = {2, 5};
try {
FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(outputFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line;
int lineNumber = 1;
while ((line = bufferedReader.readLine()) != null) {
if (isLineNumberToCopy(lineNumber, lineNumbersToCopy)) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
lineNumber++;
}
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static boolean isLineNumberToCopy(int lineNumber, int[] lineNumbersToCopy) {
for (int number : lineNumbersToCopy) {
if (lineNumber == number) {
return true;
}
}
return false;
}
}
这个示例程序将会读取指定的输入文件,复制第2行和第5行的内容到一个新的输出文件中。你可以根据实际需要修改输入文件路径、输出文件路径和要复制的行号。请确保目标文件夹可写入并有足够的权限。
领取专属 10元无门槛券
手把手带您无忧上云