Yahoo Answers is shutting down on 4 May 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Java PrintWriter - What's wrong?

I have the following lines of code in a program...everything is kosher in terms of imports, exceptions, variables, etc.

PrintWriter writer = new PrintWriter("Record.txt");

writer.println(firstName+" "+lastName);

All I am trying to do is write the two string variables to a text file. This should do it as far as I can tell but it only creates the file and nothing ever gets written to it. What am I doing wrong?

3 Answers

Relevance
  • 1 decade ago
    Favourite answer

    I think, you doesn’t properly close printwriter object, use the below code and modify your own requirement.

    import java.io.*;

    class X{

    public static void main(String [] args){

    try{

    PrintWriter p = new PrintWriter("D://1.txt");

    p.println("Here your content");

    p.close();

    }

    catch(Exception ex){

    ex.printStackTrace();

    }

    }

    }

    I hope this help.

  • Anonymous
    5 years ago

    I'd say the while-condition is failing right off the bat. Beginner trap #105: Assuming a file open operation will always work. Don't. Always check the return value for a failure indication and report it. Most likely reason is that the file is in the wrong directory. Hope that helps.

  • 1 decade ago

    writer.ptintln(..); would not write the data into file, it just for printing the data on console.

    you need to use writer.write(...);

    Why do you want to use PrintWriter object, why dont you use FileWriter to write the file?

    Use the following code to write the file, if you like

    Writer output = null;

    String text = "firstName";

    File file = new File("Record.txt");

    BufferedWriter output = new BufferedWriter(new FileWriter(file));

    output.write(text);

    output.close();

Still have questions? Get answers by asking now.