How do I save a String to a text file using Java?

后端 未结 24 1364
不知归路
不知归路 2020-11-22 04:18

In Java, I have text from a text field in a String variable called \"text\".

How can I save the contents of the \"text\" variable to a file?

24条回答
  •  梦如初夏
    2020-11-22 04:38

    If you only care about pushing one block of text to file, this will overwrite it each time.

    JFileChooser chooser = new JFileChooser();
    int returnVal = chooser.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        FileOutputStream stream = null;
        PrintStream out = null;
        try {
            File file = chooser.getSelectedFile();
            stream = new FileOutputStream(file); 
            String text = "Your String goes here";
            out = new PrintStream(stream);
            out.print(text);                  //This will overwrite existing contents
    
        } catch (Exception ex) {
            //do something
        } finally {
            try {
                if(stream!=null) stream.close();
                if(out!=null) out.close();
            } catch (Exception ex) {
                //do something
            }
        }
    }
    

    This example allows the user to select a file using a file chooser.

提交回复
热议问题