Java从一个文件读取并使用方法写入另一个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28290991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:56:15  来源:igfitidea点击:

Java read from one file and write into another file using methods

javafile-iobufferedreaderbufferedwriter

提问by Newbie

I am learning Java and working on File IO and right now stuck in reading text from One file and write in another file. I am using two different methods first one for reading and displaying text in console from file #1 and using another method to write in file#2.

我正在学习 Java 并处理文件 IO,现在卡在从一个文件中读取文本并写入另一个文件中。我使用两种不同的方法,第一种是从文件 #1 读取和显示控制台中的文本,另一种方法是在文件 #2 中写入。

I can successfully read and display contents from File#1 but not sure how to write the text in file#2.

我可以成功读取和显示文件#1 中的内容,但不确定如何在文件#2 中写入文本。

Here is the code which I have written so far:

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

import java.io.*;
public class ReadnWrite {
    public static void readFile() throws IOException {
        BufferedReader inputStream = new BufferedReader(new FileReader(
                "original.txt"));
        String count;
        while ((count = inputStream.readLine()) != null) {
            System.out.println(count);
        }
        inputStream.close();
    }
    public static void writeFile() throws IOException{
        BufferedWriter outputStream = new BufferedWriter(new FileWriter(
        "numbers.txt"));

//Not sure what comes here
    }
    public static void main(String[] args) throws IOException {
        checkFileExists();
        readFile();
    }
}

This is just for my own learning as there are lots of examples to read and write without using different methods but I want tolearn how I can achieve through different methods.

这只是为了我自己的学习,因为有很多例子可以在不使用不同方法的情况下阅读和编写,但我想学习如何通过不同的方法来实现。

Any help will be highly appreciated.

任何帮助将不胜感激。

Regards,

问候,

采纳答案by jnd

You can write to another file using: outputStream.write(). And when you are done just outputStream.flush()and outputStream.close().

您可以使用: 写入另一个文件 outputStream.write()。当你完成时,outputStream.flush()outputStream.close()

Edit:

编辑:

public void readAndWriteFromfile() throws IOException {
    BufferedReader inputStream = new BufferedReader(new FileReader(
            "original.txt"));
     File UIFile = new File("numbers.txt");
        // if File doesnt exists, then create it
        if (!UIFile.exists()) {
            UIFile.createNewFile();
        }
    FileWriter filewriter = new FileWriter(UIFile.getAbsoluteFile());
    BufferedWriter outputStream= new BufferedWriter(filewriter);
    String count;
    while ((count = inputStream.readLine()) != null) {
        outputStream.write(count);
    }
    outputStream.flush();
    outputStream.close();
    inputStream.close();

回答by Maher Abuthraa

Here is my way how to copy files:

这是我如何复制文件的方法:

BufferedReader br = null;
BufferedWriter bw = null;

try {
    br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("origin.txt"))));
    bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("target.txt"))));

    int i;
    do {
        i = br.read();
        if (i != -1) {
            bw.write(i);
        }
    } while (i != -1);

} catch (IOException e) {
    System.err.println("error during copying: "+ e.getMessage());
} finally {
    try {
        if (br != null) br.close();
        if (bw != null) bw.close();
    } catch (IOException e) {
        System.err.println("error during closing: "+ e.getMessage());
    }
}

回答by xtra

I'd use a BufferedReaderthat wraps a FileReaderand a BufferedWriterthat wraps a FileWriter.

我会使用一个BufferedReader包装 aFileReader和一个BufferedWriter包装 a FileWriter

Since you want to do it using two different methods you have to store the data in a List<String> datato pass it between the methods.

由于您想使用两种不同的方法来完成它,因此您必须将数据存储在 a 中List<String> data以在方法之间传递它。

public class ReadnWrite {

    public static List<String> readFile() throws IOException {
        try(BufferedReader br = new BufferedReader(new FileReader("original.txt"))){
            List<String> listOfData = new ArrayList<>();
            String d;
            while((d = br.readLine()) != null){
                listOfData.add(d);
            }
            return listOfData;
        }
    }

    public static void writeFile(List<String> listOfData) throws IOException{
        try(BufferedWriter bw = new BufferedWriter(new FileWriter("numbers.txt"))){
            for(String str: listOfData){
                bw.write(str);
                bw.newLine();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        List<String> data = readFile();
        writeFile(data);
    }
}

As an alternative, if you don't have to do operations on the data between read and write I'd also do it in one method.

作为替代方案,如果您不必在读取和写入之间对数据进行操作,我也会使用一种方法进行操作。

public class CopyFileBufferedRW {

    public static void main(String[] args) {
        File originalFile = new File("original.txt");
        File newFile = new File(originalFile.getParent(), "numbers.txt");

        try (BufferedReader br = new BufferedReader(new FileReader(originalFile));
             BufferedWriter bw = new BufferedWriter(new FileWriter(newFile))) {
            String s;
            while ((s = br.readLine()) != null) {
                bw.write(s);
                bw.newLine();
            }
        } catch (IOException e) {
            System.err.println("error during copying: " + e.getMessage());
        }
    }
}