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

后端 未结 24 1103
不知归路
不知归路 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:55

    If you wish to keep the carriage return characters from the string into a file here is an code example:

        jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
        orderButton = new JButton("Execute");
        textArea = new JTextArea();
        ...
    
    
        // String captured from JTextArea()
        orderButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                // When Execute button is pressed
                String tempQuery = textArea.getText();
                tempQuery = tempQuery.replaceAll("\n", "\r\n");
                try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
                    out.print(tempQuery);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println(tempQuery);
            }
    
        });
    

提交回复
热议问题