如何使用 Java 将字符串保存到文本文件?

发布于 2024-07-26 10:01:47 字数 76 浏览 6 评论 0原文

在 Java 中,我有来自名为“text”的字符串变量中的文本字段的文本。

如何将“text”变量的内容保存到文件中?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

朱染 2024-08-02 10:01:47

如果您只是输出文本,而不是任何二进制数据,则以下操作将起作用:

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

然后,将字符串写入其中,就像写入任何输出流一样:

out.println(text);

您将一如既往地需要异常处理。 完成写入后请务必关闭输出流。

out.close()

如果您使用的是 Java 7 或更高版本,则可以使用“try-with -resources 语句”,当您完成它(即退出块)时,它将自动关闭您的 PrintStream ,如下所示:

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

您仍然需要显式抛出 java.io .FileNotFoundException 和以前一样。

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 close the output stream when you've finished writing.

out.close()

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.

岛徒 2024-08-02 10:01:47

Apache Commons IO 包含一些很棒的方法来执行此操作,特别是 FileUtils 包含以下方法:

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

它允许您在一个方法调用中将文本写入文件:

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

您可能还需要考虑指定文件的编码。

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.

暮年慕年 2024-08-02 10:01:47

在 Java 7 中你可以这样做:

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

这里有更多信息:
http://www.drdobbs.com/jvm/java -se-7-new-file-io/231600403

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

木落 2024-08-02 10:01:47

查看 Java 文件 API

一个简单的例子:

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

Take a look at the Java File API

a quick example:

try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
    out.print(text);
}
贵在坚持 2024-08-02 10:01:47

刚刚在我的项目中做了类似的事情。 使用 FileWriter 将简化您的部分工作。 在这里您可以找到不错的教程

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

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)
    {
    }
}
铁憨憨 2024-08-02 10:01:47

使用 Apache Commons IO 中的 FileUtils.writeStringToFile()。 无需重新发明这个特定的轮子。

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

岁吢 2024-08-02 10:01:47

在 Java 11 中,java.nio.file.Files 类通过两个新的实用方法进行了扩展,用于将字符串写入文件。 第一种方法(参见JavaDoc 此处) 使用字符集 UTF-8 默认:

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

第二种方法(参见 JavaDoc 此处) 允许指定个人字符集:

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

两种方法都有一个可选的 Varargs 参数,用于设置文件处理选项(请参阅 JavaDoc 此处)。 以下示例将创建一个不存在的文件或将字符串附加到现有文件中:

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

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);
雾里花 2024-08-02 10:01:47

您可以使用修改下面的代码来从处理文本的任何类或函数写入文件。 人们想知道为什么世界需要一个新的文本编辑器......

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

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();
        }
    }
}
匿名。 2024-08-02 10:01:47

我更喜欢尽可能依赖库来进行此类操作。 这使得我不太可能意外地遗漏重要的步骤(就像上面狼鹬犯的错误一样)。 上面推荐了一些库,但我最喜欢的就是 Google Guava。 Guava 有一个名为 Files 非常适合此任务:

// 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
}

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
}
妖妓 2024-08-02 10:01:47

如果您需要基于一个字符串创建文本文件:

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

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();
        }
    }
}
桃扇骨 2024-08-02 10:01:47

使用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);
}

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);
}
末骤雨初歇 2024-08-02 10:01:47

使用 Apache Commons IO API。 其简单

使用 API 作为

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

Maven 依赖项

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

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>
神仙妹妹 2024-08-02 10:01:47

使用这个,它非常可读:

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

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

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);
笔芯 2024-08-02 10:01:47
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

您可以将此方法插入到您的类中。 如果您在具有 main 方法的类中使用此方法,请通过添加 static 关键字将该类更改为静态。 无论哪种方式,您都需要导入 java.io.* 才能使其工作,否则 File、FileWriter 和 BufferedWriter 将无法被识别。

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.

墨小沫ゞ 2024-08-02 10:01:47

你可以这样做:

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

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 ;
    }
};
萌吟 2024-08-02 10:01:47

使用 org.apache.commons.io.FileUtils:

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

Using org.apache.commons.io.FileUtils:

FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());
许久 2024-08-02 10:01:47

如果您只关心将一个文本块推送到文件,则每次都会覆盖它。

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

此示例允许用户使用文件选择器选择文件。

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.

离线来电— 2024-08-02 10:01:47

基本上与这里的答案相同,但易于复制/粘贴,而且它可以正常工作;-)

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

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);
    }
  }
喜爱纠缠 2024-08-02 10:01:47
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);
    }
}
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);
    }
}
断肠人 2024-08-02 10:01:47

最好在finally块中关闭编写器/输出流,以防万一发生什么情况

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

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();
     }
   }
}
┈┾☆殇 2024-08-02 10:01:47

我认为最好的方法是使用 Files.write(Path path, Iterablelines, OpenOption... options)

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

参见 javadoc:

将文本行写入文件。 每一行都是一个字符序列,并且是
按顺序写入文件,每行以
平台的行分隔符,由系统属性定义
行.分隔符。 使用指定的字符编码为字节
字符集。

选项参数指定如何创建或打开文件。
如果不存在任何选项,则此方法的工作方式与 CREATE 一样,
TRUNCATE_EXISTING 和 WRITE 选项存在。 换句话说,它
打开文件进行写入,如果文件不存在则创建该文件,或者
最初将现有常规文件截断为大小 0。
方法确保文件在所有行都已关闭后关闭
写入(或者抛出 I/O 错误或其他运行时异常)。 如果
发生 I/O 错误,则可能会在文件创建后发生,或者
被截断,或者在将一些字节写入文件后。

请注意。 我看到人们已经用 Java 的内置 Files.write 进行了回答,但是我的回答中的特别之处似乎没有人提到的是该方法的重载版本,该方法采用 CharSequence 的 Iterable(即字符串) ,而不是 byte[] 数组,因此不需要 text.getBytes() ,我认为这更干净一些。

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.

扮仙女 2024-08-02 10:01:47

如果您希望将字符串中的回车符保留到文件中
这是一个代码示例:

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

    });

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

    });
如何视而不见 2024-08-02 10:01:47

我发布了一个保存文件的库,只需一行代码即可处理所有内容,您可以在这里找到它及其文档

Github 存储库

你的问题的答案很简单

String path = FileSaver
        .get()
        .save(string.getBytes(),"file.txt");

I have published a library that saves files, and handles everything with one line of code only, you can find it here along with its documentation

Github repository

and the answer to your question is so easy

String path = FileSaver
        .get()
        .save(string.getBytes(),"file.txt");
梦幻之岛 2024-08-02 10:01:47

由于在所有Android版本上运行并且需要影响URL/URI等资源,因此我的方式是基于流的,欢迎任何建议。

就流(InputStream 和 OutputStream)而言,传输的是二进制数据,当开发人员要向流中写入字符串时,必须首先将其转换为字节,或者换句话说,对其进行编码。

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

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文