1

我想获取用户选择的一个文本文件的内容并将其添加到另一个文本文件而不替换当前内容。例如:

更新:如何以编号方式将其添加到第二个文件中?

文本文件 1:

AAA BBB CCC

AAA BBB CCC

TextFile2:(复制后)

  1. EEE FFF GGG

  2. AAA BBB CCC

  3. AAA BBB CCC

更新:我不得不删除我的代码,因为它可能被认为是抄袭,这已经得到回答,所以我知道该怎么做,感谢大家帮助我。

4

5 回答 5

2

试试这个 你必须使用

new FileWriter(fileName,append);

这将以附加模式打开文件:

根据javadoc它说

参数: fileName String 系统相关的文件名。

append boolean 如果为真,那么数据将被写入文件的末尾而不是开头。

public static void main(String[] args) {
    FileReader Read = null;
    FileWriter Import = null;
    try {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a file name: ");
        System.out.flush();
        String filename = scanner.nextLine();
        File file = new File(filename);
        Read = new FileReader(filename);
        Import = new FileWriter("songstuff.txt",true);
        int Rip = Read.read();

        while(Rip!=-1) {
            Import.write(Rip);
            Rip = Read.read();
        }


    } catch(IOException e) {
        e.printStackTrace();
    } finally {
        close(Read);
        close(Import);
    }
}


public static void close(Closeable stream) {
    try {
        if (stream != null) {
            stream.close();
        }
    } catch(IOException e) {
       // JavaProgram();
    }
}
于 2013-10-22T09:49:17.870 回答
1

Use new FileWriter("songstuff.txt", true); to append to the file instead of overwriting it.

Refer : FileWriter

于 2013-10-22T09:16:43.140 回答
1

您可以使用 Apache commons IO。

Apache Commons IO

例子:

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.commons.io.FileUtils;

public class HelpTest {

    public static void main(String args[]) throws IOException, URISyntaxException {

        String inputFilename = "test.txt"; // get from the user

        //Im loading file from project
        //You might load from somewhere else...
        URI uri = HelpTest.class.getResource("/" + inputFilename).toURI();
        String fileString = FileUtils.readFileToString(new File(uri));

        // output file
        File outputFile = new File("C:\\test.txt");
        FileUtils.write(outputFile, fileString, true);
    }
}
于 2013-10-22T09:26:27.737 回答
0

Append the file

Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

new FileWriter(fileName,true);
于 2013-10-22T09:18:01.150 回答
0

为写入而打开的文件通道可能处于附加模式.. http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html

也看看.. http://docs.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File , boolean)

于 2013-10-22T09:27:20.233 回答