RODDYGINGER
RODDYGINGER

Reputation: 19

Need to output Strings to a .txt file

I'm at my wits end here, me and a friend have been trying to get user input and write that to a .txt file but I have no idea where I'm gone wrong...

public static void main (String [] args)
{
    toTxtFile();

}

static void toTxtFile()
{
    //Scanner in = new Scanner (System.in);

    try 
    {
        File records = new File("C:\\Users\\rodriscolljava\\Desktop\\IOFiles\\test3.txt");

        records.createNewFile();

        FileWriter fw = new FileWriter(records, true);

        PrintWriter pw = new PrintWriter(fw);

        String str = JOptionPane.showInputDialog(null,"Enter your text below");

        str = str.toUpperCase();

        pw.println(str);

        if (str.length() == 3 && str.contains("END"))
        {
            JOptionPane.showMessageDialog(null, "You've ended the task","ERROR",JOptionPane.ERROR_MESSAGE);
            pw.flush();
            pw.close();


            //in.close();
        }
        else 
        {

            pw.println(str);

            toTxtFile();
        }

    }
    catch (IOException exc)
    {
        exc.printStackTrace();
    }

}

}

I've tried putting the loop as a do/while with far from good results, any help would be appreciated D:

Upvotes: 1

Views: 55

Answers (2)

Vishal Gajera
Vishal Gajera

Reputation: 4207

you have to add ,

pw.flush();

after pw.println(str);

and want to do it again and again then put it into while loop likewise,

while(true){
                String str = JOptionPane.showInputDialog(null,"Enter your text below");

                str = str.toUpperCase();

                if (str.length() == 3 && str.contains("END"))
                {
                    JOptionPane.showMessageDialog(null, "You've ended the task","ERROR",JOptionPane.ERROR_MESSAGE);
                    break;
                }

                pw.println(str); // else write to file...
                pw.flush();

            }
            pw.flush();
            pw.close();

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201409

You can use a try-with-resources to close when you're done; and you might use an infinite loop with a break like

static void toTxtFile() {
    File records = new File("C:\\Users\\rodriscolljava\\Desktop\\IOFiles\\test3.txt");
    try (PrintWriter pw = new PrintWriter(records)) {
        while (true) {
            String str = JOptionPane.showInputDialog(null, "Enter your text below");
            str = str.toUpperCase();
            if (str.equals("END")) {
                JOptionPane.showMessageDialog(null, "You've ended the task", 
                            "ERROR", JOptionPane.ERROR_MESSAGE);
                break;
            }
            pw.println(str);
        }
    } catch (IOException exc) {
        exc.printStackTrace();
    }
}

Upvotes: 2

Related Questions