如何在java中更改文本文件内容

时间:2017-02-19 11:22:44

标签: java

我有包含

的website.txt文件
google  
facebook  
twitter   
bing  
youtube

我想用

编辑该文件
www.google.com  
www.facebook.com  
www.twitter.com  
www.bing.com  
www.youtube.com    

如何使用java中的文件操作

2 个答案:

答案 0 :(得分:0)

您可以使用ReaderWriter类来执行读/写操作,例如:

public static void main(String[] args) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader("")); FileWriter writer = new FileWriter("");) {
        String line;

        while ((line = reader.readLine()) != null) {
            writer.write("www." + line + ".com");
            writer.write("\n");
        }
    }
}

答案 1 :(得分:0)

如果您使用Java 8,则可以按如下方式执行:

try (Stream<String> stream = Files.lines(Paths.get("your_input_file"))) {
            try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("you_output_file"))) {
                stream.map(line -> new String("www." + line + ".com\n")).forEach(line -> {
                    try {
                        writer.write(line);
                    } catch (IOException e) {}
                });
            }

        } catch (IOException e) {}