Java中的文件操作(更改文件中的行)

时间:2019-03-16 05:05:06

标签: java file-manipulation

我正在尝试读取文件并更改某些行。

该指令显示为“调用java Exercise12_11 John文件名会从指定文件中删除字符串John。”

这是我到目前为止编写的代码

import java.util.Scanner;
import java.io.*;
public class Exercise12_11 {

public static void main(String[] args) throws Exception{

    System.out.println("Enter a String and the file name.");

    if(args.length != 2) {
        System.out.println("Input invalid. Example: John filename");
        System.exit(1);
    }
    //check if file exists, if it doesn't exit program
    File file = new File(args[1]);
    if(!file.exists()) {
        System.out.println("The file " + args[1] + " does not exist");
        System.exit(2);
    }
    /*okay so, I need to remove all instances of the string from the file. 
     * replacing with "" would technically remove the string
     */
    try (//read in the file
            Scanner in = new Scanner(file);) {


        while(in.hasNext()) {
            String newLine = in.nextLine();
            newLine = newLine.replaceAll(args[0], "");
            }

    }

}

}

我不太清楚我是否朝着正确的方向前进,因为在使命令行与我一起使用时遇到问题。我只想知道这是否朝着正确的方向发展。

这实际上是在更改当前文件中的行,还是我需要其他文件进行更改?我可以将其包装在PrintWriter中进行输出吗?

编辑:拿出一些不必要的信息来关注问题。有人评论说该文件将不会被编辑。这是否意味着我需要使用PrintWriter。我可以只创建一个文件吗?意思是我不从用户那里获取文件?

1 个答案:

答案 0 :(得分:0)

您的代码仅读取文件并将行保存到内存中。您将需要存储所有修改后的内容,然后将其重新写回到文件中。

此外,如果在重新写回文件时需要保留换行符\n以保持格式,请确保将其包括在内。

有许多解决方法,这就是其中一种。它并不完美,但是可以解决您的问题。您可以从中获得一些想法或指示。

List<String> lines = new ArrayList<>();
try {
    Scanner in = new Scanner(file);

    while(in.hasNext()) {
        String newLine = in.nextLine();
        lines.add(newLine.replaceAll(args[0], "") + "\n"); // <-- save new-line character
    }

    in.close();

    // save all new lines to input file
    FileWriter fileWriter = new FileWriter(args[1]);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    lines.forEach(printWriter::print);
    printWriter.close();

} catch (IOException ioEx) {
    System.err.println("Error: " + ioEx.getMessage());
}