ChatGPT解决这个技术问题 Extra ChatGPT

How do I save a String to a text file using Java?

In Java, I have text from a text field in a String variable called "text".

How can I save the contents of the "text" variable to a file?


0
030

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. Be sure to call out.close() when you've finished writing.

If you are using Java 7 or later, you can use the "try-with-resources statement" which will automatically close your PrintStream when you are done with it (ie exit the block) like so:

try (PrintWriter out = new PrintWriter("filename.txt")) {
    out.println(text);
}

You will still need to explicitly throw the java.io.FileNotFoundException as before.


@Justin, you could also pass an absolute path (e.g. "/tmp/filename.txt") to the FileOutputStream constructor, to save the file anywhere you want
Btw, this could be simplified using the convenience constructors PrintStream has had since 1.5. This would suffice: PrintStream out = new PrintStream("filename.txt");
Need to close that file though at some point...? codecodex.com/wiki/ASCII_file_save#Java
You want to use try{} catch(){}finally{}, where in finally{} you close the file if it is not null.
In java8 you can try(PrintStream ps = new PrintStream("filename")) { ps.println(out); } this will handle close for you
t
tostao

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

static void writeStringToFile(File file, String data, Charset charset) 

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

FileUtils.writeStringToFile(new File("test.txt"), "Hello File", Charset.forName("UTF-8"));

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


Just a minor correction, the second fragment should read: FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
For those of us who prefer Guava, it can do this too.
The function is now deprecated, you should add the default charset --> FileUtils.writeStringToFile(new File("test.txt"), "Hello File", forName("UTF-8"));
D
Daniil Shevelev

In Java 7 you can do this:

String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());

There is more info here: http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403


In case someone later wondered, the encoding would be the platform standard.
content.getBytes(StandardCharsets.UTF_8) can be used to explicitly define the encoding.
Note that StandardOpenOption.CREATE is not the default one StandardOpenOption.CREATE and StandardOpenOption.TRUNCATE_EXISTING is the default. To use the default just remove the third parameter.
Please see Tinus Tate's comment! What is the process to edit this example? I wonder how many thousands of people have taken this example as-is only to find that they have unexpected results when they overwrite a file with a shorter string. As Tinus indicates, TRUNCATE_EXISTING is crucial unless you fully understand and have an actual reason for not wanting to truncate the existing file when overwriting with a shorter string.
In java 11 you can simply put a String as a second parameter! Hooray!
e
everton

Take a look at the Java File API

a quick example:

try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
    out.print(text);
}

@XP1 I know, that's a great improvement. I've used Lombok for this in Java 6: just go @Cleanup new FileOutputStream(...) and you're done.
Don't forget to call out.flush(); then out.close();
@AlexByrth why should he?
Large files are recorded in the background (another thread) and take time to record. Calling flush () ensures that everything has been written on the next line, synchronizing the operation. But this is optional, but good practice if you handle large files, as logs.
Note that out.close() already flushes the stream, which means it is not necessary to call out.flush().
D
Dave Jarvis

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)
    {
    }
}

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);
Wrapping a FileWriter in a BufferedWriter is superfluous when you're writing out the entire file in a single write() call.
It seems that .close() doesn't throw (at least in Java 7?), is the last trycatch perhaps redundant?
Swallowing exceptions like that is going to make life hard for you when exceptions really do occur. At the very least you should rethrow them: throw new RuntimeException(e);
A
Ankur

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


I couldn't disagree more. These libraries are there so we don't introduce subtle bugs in such a simple solution.
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?
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.
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.
I implemented this without commons and got a less than obvious exception thrown. I then implemented this using commons and it told me exactly what was wrong. Moral of the story: why live in the dark ages if you don't have to?
M
Marcel

In Java 11 the java.nio.file.Files class was extended by two new utility methods to write a string into a file. The first method (see JavaDoc here) uses the charset UTF-8 as default:

Files.writeString(Path.of("my", "path"), "My String");

And the second method (see JavaDoc here) allows to specify an individual charset:

Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);

Both methods have an optional Varargs parameter for setting file handling options (see JavaDoc here). The following example would create a non-existing file or append the string to an existing one:

Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);

This needs more upvotes. The answer gets buried in the amount of answers provided to this question, yet it is superior to many of them. E.g. only a minimal amount of lines is required, there is also no dependency on Apache Commons.
A
Adam Wagner

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();
        }
    }
}

That doesn't close the file in case of an exception.
@JanusTroelsen: If rejected, cite The try-with-resources Statement.
J
Janus Troelsen

I prefer to rely on libraries whenever possible for this sort of operation. This makes me less likely to accidentally omit an important step (like mistake wolfsnipes made above). Some libraries are suggested above, but my favorite for this kind of thing is Google Guava. Guava has a class called Files which works nicely for this task:

// This is where the file goes.
File destination = new File("file.txt");
// This line isn't needed, but is really useful 
// if you're a beginner and don't know where your file is going to end up.
System.out.println(destination.getAbsolutePath());
try {
    Files.write(text, destination, Charset.forName("UTF-8"));
} catch (IOException e) {
    // Useful error handling here
}

If you're using Guava, there is also Charsets.UTF-8.
@florian: It's Charsets.UTF_8 actually
The parent folder must exist. Example: destination.mkdirs().
Files.write(CharSequence from, File to, Charset charset) is deprecated in guava 26.0.
Modern Guava alternative to deprecated Files.write: Files.asCharSink(file, charset).write(text)
B
BullyWiiPlaza

Using Java 7:

public static void writeToFile(String text, String targetFilePath) throws IOException
{
    Path targetPath = Paths.get(targetFilePath);
    byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
    Files.write(targetPath, bytes, StandardOpenOption.CREATE);
}

A word to the wise - this will create a new file if it isn't there, but will overwrite the characters of the existing file if it is. If the new data is smaller, that will mean you probably create a corrupted file. Ask me how I know!
Ok, how do you know?
Just use Files.write(targetPath, bytes); to overwrite the file then. It will work as expected.
P
Pavel_H

In case if you need create text file based on one single string:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class StringWriteSample {
    public static void main(String[] args) {
        String text = "This is text to be saved in file";

        try {
            Files.write(Paths.get("my-file.txt"), text.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Files.write(path, byte[]) will use UTF-8 encoding. String.getBytes() uses the default platform encoding. So this is a potential issue. Use string.getBytes(StandardCharsets.UTF_8)!
A
Anirban Chakrabarti

Use Apache Commons IO api. Its simple

Use API as

 FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");

Maven Dependency

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

B
BDL

Use this, it is very readable:

import java.nio.file.Files;
import java.nio.file.Paths;

Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);

It's also a copy of an existing answer. :c
sorry but i didn't invent java8 , i am not the only one that use this line . but it is not a copy past from other answers to the same question
S
Sean H. Worthington
import java.io.*;

private void stringToFile( String text, String fileName )
 {
 try
 {
    File file = new File( fileName );

    // if file doesnt exists, then create it 
    if ( ! file.exists( ) )
    {
        file.createNewFile( );
    }

    FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
    BufferedWriter bw = new BufferedWriter( fw );
    bw.write( text );
    bw.close( );
    //System.out.println("Done writing to " + fileName); //For testing 
 }
 catch( IOException e )
 {
 System.out.println("Error: " + e);
 e.printStackTrace( );
 }
} //End method stringToFile

You can insert this method into your classes. If you are using this method in a class with a main method, change this class to static by adding the static key word. Either way you will need to import java.io.* to make it work otherwise File, FileWriter and BufferedWriter will not be recognized.


j
javaPlease42

You could do this:

import java.io.*;
import java.util.*;

class WriteText
{
    public static void main(String[] args)
    {   
        try {
            String text = "Your sample content to save in a text file.";
            BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
            out.write(text);
            out.close();
        }
        catch (IOException e)
        {
            System.out.println("Exception ");       
        }

        return ;
    }
};

B
BullyWiiPlaza

Using org.apache.commons.io.FileUtils:

FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());

E
Eric Leschinski

If you only care about pushing one block of text to file, this will overwrite it each time.

JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
    FileOutputStream stream = null;
    PrintStream out = null;
    try {
        File file = chooser.getSelectedFile();
        stream = new FileOutputStream(file); 
        String text = "Your String goes here";
        out = new PrintStream(stream);
        out.print(text);                  //This will overwrite existing contents

    } catch (Exception ex) {
        //do something
    } finally {
        try {
            if(stream!=null) stream.close();
            if(out!=null) out.close();
        } catch (Exception ex) {
            //do something
        }
    }
}

This example allows the user to select a file using a file chooser.


@Eric Leschinski : thank you for making my answer more professional (i also assumed this was exactly what the OP wanted since this is what actually most people wants,just dump the text and replace it)
Once the original question has been answered and the OP is satisfied and long-gone, pages like this serve only as a useful artifact to people who land here from a Google search. I landed on this page in order to create a mini text appender to a file. So it's good to speak to the entire audience rather than the OP after the OP has moved on.
B
Brad Parks

Basically the same answer as here, but easy to copy/paste, and it just works ;-)

  import java.io.FileWriter;

  public void saveToFile(String data, String filename) {
    try (
      FileWriter fw = new FileWriter(filename)) {
      fw.write(data);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

a
aboger
private static void generateFile(String stringToWrite, String outputFile) {
    try {       
        FileWriter writer = new FileWriter(outputFile);
        writer.append(stringToWrite);
        writer.flush();
        writer.close();
        log.debug("New File is generated ==>"+outputFile);
    } catch (Exception exp) {
        log.error("Exception in generateFile ", exp);
    }
}

While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
close() may never be called. Please, improve your answer adding the proper error case handling.
佚名

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();
     }
   }
}

even better: use try-with-resources
Yes, @JanusTroelsen is right, better use The try-with-resources statement docs.oracle.com/javase/tutorial/essential/exceptions/…
a
alb-i986

I think the best way is using Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options):

String text = "content";
Path path = Paths.get("path", "to", "file");
Files.write(path, Arrays.asList(text));

See javadoc:

Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator. Characters are encoded into bytes using the specified charset. The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0. The method ensures that the file is closed when all lines have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has created or truncated, or after some bytes have been written to the file.

Please note. I see people have already answered with Java's built-in Files.write, but what's special in my answer which nobody seems to mention is the overloaded version of the method which takes an Iterable of CharSequence (i.e. String), instead of a byte[] array, thus text.getBytes() is not required, which is a bit cleaner I think.


Q
QA Specialist

If you wish to keep the carriage return characters from the string into a file here is an code example:

    jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
    orderButton = new JButton("Execute");
    textArea = new JTextArea();
    ...


    // String captured from JTextArea()
    orderButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            // When Execute button is pressed
            String tempQuery = textArea.getText();
            tempQuery = tempQuery.replaceAll("\n", "\r\n");
            try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
                out.print(tempQuery);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(tempQuery);
        }

    });

M
Mou

My way is based on stream due to running on all Android versions and needs of fecthing resources such as URL/URI, any suggestion is welcome.

As far as concerned, streams (InputStream and OutputStream) transfer binary data, when developer goes to write a string to a stream, must first convert it to bytes, or in other words encode it.

public boolean writeStringToFile(File file, String string, Charset charset) {
    if (file == null) return false;
    if (string == null) return false;
    return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
}

public boolean writeBytesToFile(File file, byte[] data) {
    if (file == null) return false;
    if (data == null) return false;
    FileOutputStream fos;
    BufferedOutputStream bos;
    try {
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(data, 0, data.length);
        bos.flush();
        bos.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
        Logger.e("!!! IOException");
        return false;
    }
    return true;
}

Please add proper error case handling closing all opened resources and propogating exceptions