【问题标题】:FileWriter / BufferedReader Java word finderFileWriter / BufferedReader Java 单词查找器
【发布时间】:2018-11-21 09:22:54
【问题描述】:

我已经设置了这段代码,我正在尝试编写一个程序来查看文件并找到一个特定的隐藏秘密词,然后将这个词替换为“找到!”然后在控制台中重新打印文本文件。我知道如何使用 reader 和 writer,但我不确定如何同时使用它们来做到这一点。代码如下:

阅读器类:

package Main;

import java.io.*;

public class Read {

private static String line;
FileReader in;
File file;

public Read() {
    line = "";
}
public void readFile() throws IOException {
    file = new File("C:examplePathName\\ReadWriteExp.txt");
    in = new FileReader(file);
    BufferedReader br = new BufferedReader(in);
    while((line = br.readLine()) != null) {
        System.out.println(line);
    }
    in.close();
}


public String getLine() {
    return line;
}

public File getFile() {
    return file;
}

}

Writer(change) 类:

package Main;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class Change {

public static void main(String[] args) throws IOException{
    Read r = new Read();

    String line = r.getLine();
    FileWriter fw = new FileWriter(r.getFile());
    while(line != null) {
        if(line.equals("example")) {
            fw.write("found!");

        }
        System.out.println(line);
    }

}

}

我是在正确的道路上还是应该将这两者结合到一个类中。这也是写入文本文件中特定行的正确方法吗?

【问题讨论】:

  • 你没有调用 readFile() 方法然后如何读取文件。

标签: java bufferedreader filewriter


【解决方案1】:

如果文件大小合适,您可以将其读入内存,更改您需要的内容并再次将其写回:

public static void replaceOccurrences(String match, String replacement, Path path) throws IOException {
    Files.write(path, Files.lines(path).map(l -> {
        if(l.contains(match)) {
            return l.replace(match, replacement);
        } else {
            return l;
        }
    }).collect(Collectors.toList()));
}

或者,如果您知道搜索词只出现一次并且您只需要找到出现的位置,请使用以下内容:

try(BufferedReader reader = Files.newBufferedReader(path)) {
    int lineIndex = 0;
    String line;
    while(!(line = reader.readLine()).contains(match)) {
        lineIndex++;
    }
    System.out.println(lineIndex); // line which contains match, 0-indexed
    System.out.println(line.indexOf(match)); // starting position of match in line, 0-indexed
}

【讨论】:

    【解决方案2】:

    如果您只需将转换后的文本打印到系统输出(而不是将其写入文件),那么第二类就不是必需的了。您可以在 Read 类的readFile() 方法中完成您需要的操作:

    public void readFile() throws IOException {
      file = new File("C:examplePathName\\ReadWriteExp.txt");
      in = new FileReader(file);
      BufferedReader br = new BufferedReader(in);
      while((line = br.readLine()) != null) {
        System.out.println(line.replaceAll("example", "found!"));
      }
      in.close();
    }
    

    您可以进行许多其他调整,但这是您在问题中指定的功能的核心。

    【讨论】:

    • 这不能回答 OP 的问题
    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 2015-05-09
    • 2013-03-06
    相关资源
    最近更新 更多