用Java创建和写入(文本)文件的最简单方法是什么?


当前回答

如果您希望获得相对轻松的体验,还可以查看Apache Commons IO包,更具体地说是FileUtils类。

永远不要忘记检查第三方库。用于日期操作的Joda Time、用于常见字符串操作的Apache Commons Lang StringUtils等可以使代码更可读。

Java是一种很棒的语言,但标准库有时有点低级。功能强大,但级别较低。

其他回答

使用JFilechooser与客户一起阅读集合并保存到文件。

private void writeFile(){

    JFileChooser fileChooser = new JFileChooser(this.PATH);
    int retValue = fileChooser.showDialog(this, "Save File");

    if (retValue == JFileChooser.APPROVE_OPTION){

        try (Writer fileWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileChooser.getSelectedFile())))){

            this.customers.forEach((c) ->{
                try{
                    fileWrite.append(c.toString()).append("\n");
                }
                catch (IOException ex){
                    ex.printStackTrace();
                }
            });
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}
public class Program {
    public static void main(String[] args) {
        String text = "Hello world";
        BufferedWriter output = null;
        try {
            File file = new File("example.txt");
            output = new BufferedWriter(new FileWriter(file));
            output.write(text);
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
          if ( output != null ) {
            try {
                output.close();
            }catch (IOException e){
                e.printStackTrace();
            }
          }
        }
    }
}
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {
    public static void main(String [] args) {
        FileWriter fw= null;
        File file =null;
        try {
            file=new File("WriteFile.txt");
            if(!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file);
            fw.write("This is an string written to a file");
            fw.flush();
            fw.close();
            System.out.println("File written Succesfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Use:

JFileChooser c = new JFileChooser();
c.showOpenDialog(c);
File writeFile = c.getSelectedFile();
String content = "Input the data here to be written to your file";

try {
    FileWriter fw = new FileWriter(writeFile);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(content);
    bw.append("hiiiii");
    bw.close();
    fw.close();
}
catch (Exception exc) {
   System.out.println(exc);
}

如果出于某种原因想要将创建和编写行为分开,那么Java中的touch等价物是

try {
   //create a file named "testfile.txt" in the current working directory
   File myFile = new File("testfile.txt");
   if ( myFile.createNewFile() ) {
      System.out.println("Success!");
   } else {
      System.out.println("Failure!");
   }
} catch ( IOException ioe ) { ioe.printStackTrace(); }

createNewFile()执行存在性检查,并自动创建文件。例如,如果您希望在写入文件之前确保自己是文件的创建者,这可能很有用。