0

So, say I type "message" into my program. How would I get the program to create a text document displaying the text "message". This would be an external text document, preferably created in the same folder as the Java application.

UPDATE: I've found the following code from the post: How do I save a String to a text file using Java? but I still have a few questions. So first off, how would I specify where the file would be saved? Second off, how would I get the actual input? I have the question: https://stackoverflow.com/questions/37797886/how-would-i-create-a-text-input-bar-in-java-using-swing-that-would-create-an-e that will hopefully get an answer soon, but after that, how would I make the input go to a text file rather that another class?. Help would be appreciated. Sorry for the previous lack of detail ;). Thank you TerraPass for marking the question as a possible duplicate. It led me to the question How do I save a String to a text file using Java? that helped me get a possible answer to this question.

BufferedWriter writer = null;
try{
writer = new BufferedWriter( new FileWriter( yourfilename));
writer.write( yourstring);
}
catch ( IOException e){
}
finally{
try{
    if ( writer != null)
    writer.close( );
}
catch ( IOException e){
}
}
Community
  • 1
  • 1
  • 2
    Possible duplicate: http://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java – TerraPass Jun 13 '16 at 21:53

1 Answers1

1

There are quite a lot of ways to do that by now and it depend on your specific case, but this should get you started:

  String sometext = "hello file!";
    try(BufferedWriter writer = new BufferedWriter(
            new FileWriter(new File("test.txt")))) {

        writer.write(sometext);
    }

Note that you do not have to use BufferedReader, but it should be more efficient.

Silverclaw
  • 1,316
  • 2
  • 15
  • 28