views:

2700

answers:

8

I am a beginner Java programmer. I am attempting to make a simple text editor. I have got the text from the text field into a variable that's a String, called "text".

My question is, how can I save the contents of the "text" variable to a text file?

Thank you!

+2  A: 

Take a look at the Java File API

a quick example:

try {
    PrintStream out = new PrintStream(new FileOutputStream("filename.txt"));
    out.print(text);
    out.close();
} catch (IOException e) {
    e.printStackTrace();
}
Jorn
You don't want to close that file, ever?
Tom Hawtin - tackline
I said it was a quick example, not the full solution. I'll add it.
Jorn
IOFoundException?
Thorbjørn Ravn Andersen
oops...........
Jorn
Just to nitpick - if an IOException is thrown, the file will not be closed - a resource leak.
McDowell
I know... I hate all the boilerplate needed to do these basic things in Java.
Jorn
+3  A: 

Use FileUtils.writeStringToFile() from Apache Commons IO. No need to reinvent this particular wheel.

skaffman
No need for that dependency on such a simple problem.
duffymo
I couldn't disagree more. These libraries are there so we don't introduce subtle bugs in such a simple solution.
skaffman
+1 for applying "know and use the libraries"
Jonik
I couldn't disagree more. It's a "beginner Java programmer" who's trying to learn the language. I'd say learn how to code it properly once before diving into 10,001 dependencies. Even an experienced developer should weigh functionality against dependencies. And yes, I do appreciate the value of libraries. I've been using Spring for five years and counting.
duffymo
Would you suggest that he go back and re-implement java.file.IO and java.io.PrintStream in raw C? Of course not. You use the java.io abstractions, and save your effort for real problems. And Commons IO is a better abstraction than java.io when it comes to this particular problem.
skaffman
No, obviously not. I'm only disagreeing that your solution might not be the first thing I'd throw at someone who's a beginner Java programmer. You aren't suggesting that you've never written such a thing, are you?
duffymo
I have, yes, but that's before I found commons-io. Since finding that, I've never written that sort of thing by hand, even in a one-class project. If I'd known about it from day one, I'd have used it from day one.
skaffman
Exactly, but you're an experienced developer. Your bio says your a JBOSS/Spring user, but certainly you wouldn't have been up to either one in your first "Hello, World" effort. I'm not disagreeing with the proper use of libraries. I'm saying that people attempting a language for the first time should try to know it at its bottom, even if that means doing things that they'll discard later on when they're experienced and know better.
duffymo
s/your/you're. I hate when I make that error.
duffymo
+4  A: 

Just did something similar in my project. Use FileWriter will simplify part of your job. And here you can find nice tutorial.

 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)
  {
  }
     }
Artem Barger
Great, 22 lines of code to achieve what an off-the shelf library will do in 1.
skaffman
Removing all try/catch and simplify it I'm also able to do it in one line just by doing the: (new BufferedWriter( new FileWriter( filename))).write(str);
Artem Barger
That is an overly messy way to do it.
Tom Hawtin - tackline
So, show your simple and nice solution. I would be glad to learn how to do it in better way.
Artem Barger
+5  A: 

If you're simply outputting text, rather than any binary data, the following will work:

PrintWriter out = new PrintWriter("filename.txt");

Then, write your String to it, just like you would to any output stream:

out.println(text);

You'll need exception handling, as ever.

Edit: further simplified per Jonik's comments.

Jeremy Smyth
What's exception handling? Where will this file be saved?
Justin White
it'll be saved in the current directory, whatever that is as far as the JVM is concerned. Exception handling is the try{} catch(){} stuff you see in other answers :)
Jeremy Smyth
@Justin, you could also pass an absolute path (e.g. "/tmp/filename.txt") to the FileOutputStream constructor, to save the file anywhere you want
Jonik
Btw, this could be simplified using the convenience constructors PrintStream has had since 1.5. This would suffice: PrintStream out = new PrintStream("filename.txt");
Jonik
Futhermore, as we're outputting text, PrintWriter would be more appropriate, and just as convenient. From PrintStream javadocs: "The PrintWriter class should be used in situations that require writing characters rather than bytes."
Jonik
+7  A: 

Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:

static void writeStringToFile(File file, String data)

which allows you to write text to a file in one method call:

FileUtils.writeStringToFile("test.txt", "Hello File");

You might also want to consider specifying the encoding for the file as well.

Jon
+1  A: 

You can use the modify the code below to write your file from whatever class or function is handling the text. One wonders though why the world needs a new text editor...

import java.io.*;

public class Main {

public static void main(String[] args) {

    try {
        String str = "SomeMoreTextIsHere";
        File newTextFile = new File("C:/thetextfile.txt");

        FileWriter fw = new FileWriter(newTextFile);
        fw.write(str);
        fw.close();

    } catch (IOException iox) {
        //do stuff with exception
        iox.printStackTrace();
    }
}

}

wolfsnipes
That doesn't close the file in case of an exception.
Tom Hawtin - tackline
+1  A: 

Java Almanac is a good source for simple examples. It's a good place for beginners, even if it's a bit dated.

duffymo
+1  A: 

It's better to close the writer/outputstream in a finally block, just in case something happen

finally{
   if(writer != null){
     try{
        writer.flush();
        writer.close();
     }
     catch(IOException ioe){
         ioe.printStackTrace();
     }
   }
}