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

4

我正在学习Java,正在处理文件IO问题,目前遇到了从一个文件中读取文本并将其写入另一个文件的困境。我使用了两种不同的方法,第一种方法用于从文件#1中读取和显示文本,并使用另一种方法将其写入文件#2。

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

以下是我迄今为止编写的代码:

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();
    }
}

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

任何帮助都将不胜感激。

此致敬礼,


你想从 original.txt 中读取并将所有内容写入 numbers.txt 吗? - jnd
1
可能是如何编写Java文本文件的重复问题。 - void
常识啊,使用你的常识。该链接正在使用Main方法中编写的代码。我可以轻松地实现那件事,但我想使用两种不同的方法,在write方法中不使用Reader对象。 - Newbie
#Farhang Amary,请在发布任何可能的重复问题之前仔细阅读问题。我已经查看了链接,它是在Main()中写入文件,并且我不想自己编写任何愚蠢的“HELLO WORLD”文本。我想要将我从文件#1(original.txt)读取的内容写入文件#2(numbers.txt)。 - Newbie
3个回答

5
你可以使用 outputStream.write() 方法向另一个文件写入内容。当操作完成后,使用 outputStream.flush()outputStream.close() 方法。
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();

谢谢 #jnd,但如果我只使用outputStream.write();,Java 会给出错误提示:Missing argument to match .write()。而且Java怎么知道我想保存什么东西到文件中呢?我认为我需要把original.txt文件中的所有文本放入一个对象或数组中,然后在outputStream.write();中写入数组/对象的内容,以便写入numbers.txt文件。 - Newbie
你将你想要写入的内容作为参数放入函数中,例如outputStream.write("hello");outputStream.write(15); - jnd
#jnd 我觉得你没有理解我的问题,因为我是从文件#1中检索文本,并将其写入文件#2。并不是说我想在引号内自己写任何东西... - Newbie
感谢 #jnd 的回复。这几乎与我想要的相似。通过您的代码,我已经实现了我想要的结果,但是我可以问一个问题吗?例如,如果我的程序要求用户按1从文件中读取,按2写入新文件,那么如果用户按2,我是否必须使用此 BufferedReader 方法并读取文件,或者是否有一种方法,即如果用户按下1并且程序已将所有文件内容保存在数组/数组列表中,当用户按下2时,它会从该数组/数组列表中写入所有内容到文件#2。 - Newbie
你可以任选一种方式。你只需要让你的读取方法返回一个字符串数组,然后将其传递给写入方法进行写入即可。 - jnd
不需要调用outputStream.flush();..它将被outputStream.close()隐式调用。 - Maher Abuthraa

1
我会使用一个包装了FileReaderBufferedReader和一个包装了FileWriterBufferedWriter。由于您想要使用两种不同的方法,您必须将数据存储在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);
    }
}

作为另一种选择,如果您在读取和写入之间不必对数据进行操作,我也会在一个方法中完成。
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());
        }
    }
}

0

这是我复制文件的方法:

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());
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接