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


当前回答

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

其他回答

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

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
}

如果我们使用的是Java7及以上版本,并且还知道要添加(附加)到文件中的内容,我们可以使用NIO包中的newBufferedWriter方法。

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

有几点需要注意:

指定字符集编码总是一个好习惯,因此我们在类StandardCharset中有常量。代码使用try with resource语句,其中资源在try之后自动关闭。

虽然OP没有询问,但为了以防万一我们想搜索具有特定关键字的行,例如机密,我们可以使用Java中的流API:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
    if(containsJava.isPresent()){
        System.out.println(containsJava.get());
    }
} catch (IOException e) {
    e.printStackTrace();
}

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

使用输入和输出流读取和写入文件:

//Coded By Anurag Goel
//Reading And Writing Files
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class WriteAFile {
    public static void main(String args[]) {
        try {
            byte array [] = {'1','a','2','b','5'};
            OutputStream os = new FileOutputStream("test.txt");
            for(int x=0; x < array.length ; x++) {
                os.write( array[x] ); // Writes the bytes
            }
            os.close();

            InputStream is = new FileInputStream("test.txt");
            int size = is.available();

            for(int i=0; i< size; i++) {
                System.out.print((char)is.read() + " ");
            }
            is.close();
        } catch(IOException e) {
            System.out.print("Exception");
        }
    }
}

只需包含此包:

java.nio.file

然后,您可以使用以下代码编写文件:

Path file = ...;
byte[] buf = ...;
Files.write(file, buf);