0

I'm trying to simple write a quick string to a text file using Java. However when doing so my code for some reason doesn't throw any errors or exceptions but the text file is empty after clicking the button. Here is my code

btnOk.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String text = textEntered.getText();
            try{
                PrintWriter out = new PrintWriter("~\\Users\\username\\Desktop\\File1.rft");
                out.println(text);
                out.close();
            }catch(FileNotFoundException io){
                System.out.println(io.getLocalizedMessage());
            }
        }
    });

Some extra info, the username in my file path is my username I just swapped it out for this post.

Any help would be amazing, thanks a lot in advance.

4
  • 1
    Try to use an absolute path like C:\\Users\\username\\Desktop\\File1.rft Commented Mar 23, 2017 at 23:40
  • What's the value of text? Commented Mar 23, 2017 at 23:41
  • Just add some debug logging to make sure there is actually something in text. Commented Mar 23, 2017 at 23:41
  • 1
    A tilde for the home directory doesn't work like that on Windows, does it?? Commented Mar 23, 2017 at 23:52

2 Answers 2

1

Your code works fine with some small testing alterations and if you supply the full file path:

public static void main(String[] args){
        Scanner in = new Scanner(System.in);

        String text = in.nextLine();
        try{
            PrintWriter out = new PrintWriter("/Users/user/NetBeansProjects/TestForSO/src/testforso/file.txt");
            out.println(text);
            out.close();
        }catch(FileNotFoundException io){
            System.out.println(io.getLocalizedMessage());
        }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Only the shell understands ~. Java doesn't, the kernel doesn't. Use the result of System.getProperty("user.home").

As a matter of fact your path doesn't make any sense at all. It should be something like System.getProperty("user.home")+"/Desktop/File1.rft".

Note that you don't need to use backslashes in Java filenames.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.