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


当前回答

要创建文件而不覆盖现有文件,请执行以下操作:

System.out.println("Choose folder to create file");
JFileChooser c = new JFileChooser();
c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
c.showOpenDialog(c);
c.getSelectedFile();
f = c.getSelectedFile(); // File f - global variable
String newfile = f + "\\hi.doc";//.txt or .doc or .html
File file = new File(newfile);

try {
    //System.out.println(f);
    boolean flag = file.createNewFile();

    if(flag == true) {
        JOptionPane.showMessageDialog(rootPane, "File created successfully");
    }
    else {
        JOptionPane.showMessageDialog(rootPane, "File already exists");
    }
    /* Or use exists() function as follows:
        if(file.exists() == true) {
            JOptionPane.showMessageDialog(rootPane, "File already exists");
        }
        else {
            JOptionPane.showMessageDialog(rootPane, "File created successfully");
        }
    */
}
catch(Exception e) {
    // Any exception handling method of your choice
}

其他回答

我能找到的最简单的方法是:

Path sampleOutputPath = Paths.get("/tmp/testfile")
try (BufferedWriter writer = Files.newBufferedWriter(sampleOutputPath)) {
    writer.write("Hello, world!");
}

它可能只适用于1.7+。

    public static void writefromFile(ArrayList<String> lines, String destPath) {
        FileWriter fw;
        try {
            fw = new FileWriter(destPath);
            for (String str : lines) {
                fw.write(str);
            }
            fw.close();
         } catch (IOException ex) {
            JOptionPane.showMessageDialog("ERROR: exception was: " + ex.toString());
        }
        File f = new File(destPath);
        f.setExecutable(true);
    }

请注意,下面的每个代码示例都可能引发IOException。为了简洁起见,省略了Try/catch/finally块。有关异常处理的信息,请参阅本教程。

请注意,如果文件已经存在,下面的每个代码示例都将覆盖该文件

创建文本文件:

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

创建二进制文件:

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

Java 7+用户可以使用Files类写入文件:

创建文本文件:

List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

创建二进制文件:

byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);

以下是编写文件的代码,也在退出帮助内容网页时删除:

public String writeHelpContent(String filePath, String helpPageContent) throws IOException{
        logger.info("HowToUseRiskOfficeHelpService - writeHelpContent start");
        File file = new File(filePath);
        try(FileWriter fw = new FileWriter(file);){
            file.deleteOnExit();
            if(file.createNewFile()) {
                logger.info("HowToUseRiskOfficeHelpService - file created successfully");
            }else {
                logger.info("HowToUseRiskOfficeHelpService - file already exists");
            }
            fw.write(helpPageContent); 
            fw.flush();
        }

        return "Sucessfully write into help page file";
    }

Java 7+值得一试:

 Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());

看起来很有希望。。。