如何在java文件中附加数据?

时间:2015-11-12 10:10:12

标签: java file append

我只需要你的帮助。我正在学习java(OOP),现在我们正在处理文件。但我坚持如何在文件中追加数据。我编写了代码,这是显示错误的部分。有人可以帮我解决它有什么问题吗?为什么它不起作用?

 package appending;
 import java.io.FileNotFoundException;
 import java.util.Formatter;
 import java.util.Scanner;
 import java.io.FileWriter;
 import java.io.BufferedWriter;


public class open {    
Formatter output;    
public void openFile() throws FileNotFoundException {    
    output = new Formatter("E:/thisFile.txt");
}
public void addData() {    
 Scanner input = new Scanner(System.in);
 data d = new data();
 System.out.println("Enter the data");
 d.setData(input.next(),input.nextInt());
 output.format("%s","Name and CMS:\t"+d.getData());
 FileWriter fileWritter = new FileWriter(File.getPath(),true);
 BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
 bufferWritter.write(d.getData());
 bufferWritter.close();
}
public void close() {
 output.close();
}
}

2 个答案:

答案 0 :(得分:0)

创建文本文件(请注意,如果该文件已存在,则会覆盖该文件):

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

创建二进制文件(也会覆盖文件):

byte dataToWrite[] = //...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(dataToWrite);
out.close();

答案来自:How do I create a file and write to it in Java?

如果要使用FileWriter。请尝试以下代码:

//FileWriter fw = new FileWriter(new File("path/to/test.txt"), true);
FileWriter fw = new FileWriter("path/to/test.txt", true);
fw.write("This is a sentence");
fw.close();

编辑您应该遵循惯例并将您的课程大写。

答案 1 :(得分:0)

可以尝试,

public class FileAppend {

    public static void main(String[] args) {

        PrintWriter out = null;

        try{
            out = new PrintWriter(new BufferedWriter(new FileWriter("/home/rakesh/myfile.txt", true)));
            out.println("appended text");
        } catch(Exception e){
            e.printStackTrace();
        } finally{
            out.close();
        }

    }

}