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

在Java中,我来自一个名为“ text”的String变量中的文本字段中的文本。

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


#1楼

看看Java File API

一个简单的例子:

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

#2楼

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


#3楼

只是在我的项目中做了类似的事情。 使用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)
    {
    }
}

#4楼

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

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

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

out.println(text);

与以往一样,您将需要异常处理。 完成编写后,请确保调用out.close()

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

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

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


#5楼

Apache Commons IO包含一些很棒的方法,特别是FileUtils包含以下方法:

static void writeStringToFile(File file, String data) 

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

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

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


#6楼

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

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

#7楼

最好在finally块中关闭writer / outputstream,以防万一

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

#8楼

我更喜欢在任何可能的情况下都依赖库进行此类操作。 这使我不太可能意外地忽略了重要的步骤(例如上面提到的错误Wolfsnipes)。 上面建议了一些库,但是我最喜欢这种库是Google 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
}

#9楼

使用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>

#10楼

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

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

此示例使用户可以使用文件选择器选择文件。


#11楼

在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


#12楼

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。


#13楼

您可以使用ArrayList来放置TextArea的所有内容作为示例,并通过调用save来作为参数发送,因为编写者刚刚编写了字符串行,然后我们使用“ for”一行一行地最后编写我们的ArrayList我们将在txt文件中使用TextArea内容。 如果没有什么意义,对不起,我是google翻译者,我不会说英语。

观看Windows记事本,它并不总是跳行,而是全部显示在一行中,请使用写字板确定。


私人无效SaveActionPerformed(java.awt.event.ActionEvent evt){

String NameFile = Name.getText();
ArrayList< String > Text = new ArrayList< String >();

Text.add(TextArea.getText());

SaveFile(NameFile, Text);

}


公共无效SaveFile(字符串名称,ArrayList <String>消息){

path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";

File file1 = new File(path);

try {

    if (!file1.exists()) {

        file1.createNewFile();
    }


    File[] files = file1.listFiles();


    FileWriter fw = new FileWriter(file1, true);

    BufferedWriter bw = new BufferedWriter(fw);

    for (int i = 0; i < message.size(); i++) {

        bw.write(message.get(i));
        bw.newLine();
    }

    bw.close();
    fw.close();

    FileReader fr = new FileReader(file1);

    BufferedReader br = new BufferedReader(fr);

    fw = new FileWriter(file1, true);

    bw = new BufferedWriter(fw);

    while (br.ready()) {

        String line = br.readLine();

        System.out.println(line);

        bw.write(line);
        bw.newLine();

    }
    br.close();
    fr.close();

} catch (IOException ex) {
    ex.printStackTrace();
    JOptionPane.showMessageDialog(null, "Error in" + ex);        

}


#14楼

使用它,它非常可读:

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

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

#15楼

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

#16楼

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

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

#17楼

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

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

#18楼

我认为最好的方法是使用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));

参见javadoc

将几行文字写入文件。 每行都是一个char序列,并按顺序写入到文件中,每行由平台的行分隔符终止,这由系统属性line.separator定义。 使用指定的字符集将字符编码为字节。

options参数指定如何创建或打开文件。 如果不存在任何选项,则此方法就像存在CREATE,TRUNCATE_EXISTING和WRITE选项一样工作。 换句话说,它打开文件进行写入,如果不存在则创建文件,或者首先将现有的常规文件截断为0。该方法可确保在写入所有行后关闭文件(或引发I / O错误或其他运行时异常)。 如果发生I / O错误,则可以在创建或截断文件后,或者在将某些字节写入文件后,执行此操作。

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


#19楼

如果您希望将回车符从字符串保留到文件中,请参见以下代码示例:

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

    });

#20楼

我的方法基于所有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;
}

#21楼

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

#22楼

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

}


#23楼

您可以这样做:

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 ;
    }
};
  • 6
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值