如何使用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 exceptioniox.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 pressedString 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 blocke.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 ;}
};
如何使用Java将字符串保存到文本文件?相关推荐
- java把信息存到文件里,Java 如何将字符串信息直接写保存到文本文件?
如何将字符串信息直接写保存到文本文件? Java 提供了很方便的方法,代码如下: import java.io.File; import java.io.StringWriter; /** * 传入文 ...
- Collection的使用 字符串保存 java
Collection的使用 字符串保存 java 创建集合 添加成员 获取长度 删除成员 按数据删除 清空集合 增强for遍历集合 使用迭代器 判断成员是否存在 判断是否为空 如果为空,就是true
- java 中文 音序,java 中文字符串数组按照音序排列
java 中文字符串数组按照音序排列 复制代码 代码如下: public class SortComparator implements Comparator{ public int compare( ...
- 日期居然用字符串保存?我笑了
本文经授权转载自微信公众号:后端进阶 我发现数据库有些日期居然用字符串保存?于是跟几个小伙伴讨论了关于数据库的日期应该要怎么保存的问题,其实我一直都建议直接用数值保存时间戳,为什么我要这么建议呢? 以 ...
- c++中string插入一个字符_Java内存管理-探索Java中字符串String(十二)
做一个积极的人 编码.改bug.提升自己 我有一个乐园,面向编程,春暖花开! 一.初识String类 首先JDK API的介绍: public final class String extends O ...
- Java操作Mongodb 保存/读取java对象到/从mongodb
从 http://central.maven.org/maven2/org/mongodb/mongo-java-driver/选择一个版本进行下载,这里选择的是3.0.0版本,具体下载以下jar包: ...
- JAVA获取字符串首字拼音和全拼
JAVA获取字符串首字拼音或者全部拼音,用的是pinyin4j. import java.util.ArrayList; import java.util.Hashtable; import java ...
- java反转字符串的方法
1.首先我们定义一个方法,用来反转字符串.用 public static void (String)方法初始化一个对象,然后使用 private static ()方法对该对象进行初始化,并检查是否有 ...
- 用java实现字符串的加密_JAVA 字符串加密、密码加密实现方法
在我们的程序设计中,我们经常要加密一些特殊的内容,今天总结了几个简单的加密方法,分享给大家! 如何用java实现字符串简单加密解密?为保证用户信息安全,系统在保存用户信息的时候,务必要将其密码加密保存 ...
最新文章
- [十九]JavaIO之PipedReader 和 PipedWriter
- 中国首次纳米孔测序大会:不可错过的教学专场和技术诊断
- POJ 2752 同一个串的前后串
- mysql load data 语法_MySql LOAD DATA 使用
- Codeforces 986A. Fair(对物品bfs暴力求解)
- lambda函数 RUNOOB python练习题49
- 拥抱变化——从Atlas到ASP.NET AJAX(4):大大简化的了的Extender扩展器控件
- 融资13亿后突然死亡!首款产品被苹果点赞,与谷歌竞赛的明星创业公司Anki倒闭...
- 在Linux上运行ASP.NET vNext
- 如何用xmlspy将xml文档生成xsd文件
- 初次联系导师短信模板_申博经验分享|如何联系导师?
- TIdTCPClient 详解
- w ndows无法连接到无线网络,windows无法连接到无线网络,详细教您windows无法连接到无线网络怎么办...
- QT读写文本文件编码设置
- 物流系统管理课程(二)
- 软件开发过程中常见漏洞的解析
- RC滤波分析计算——信号与系统
- 塑胶卡扣弹性计算公式_塑胶产品结构设计 卡扣
- 数据库原理及应用期末复习汇总(附某高校期末真题试卷)
- STM32WL55-NUCLEO开发(1)----STM32WLLoRaWAN介绍
热门文章
- 清除Linux和window等系统的DNS缓存的命令
- Apache Solrj EmbeddedSolrServer使用
- GdiPlus[16]: IGPLinearGradientBrush 之 SetBlendBellShape、SetBlendTriangularShape
- 2008年12月信息处理技术员上午试卷 51CTO版参考答案
- 老婆回家时没有帮老婆打点,也完全忘记提醒老婆晚上火车上很凉,内疚.亲爱的,对不起!...
- 从yield 到yield from再到python协程
- 函数(定义、参数、return、变量、作用域、预解析)
- 解决SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的 STATEMENT 'OpenRowset/OpenDatasource' 的访问...
- 数据类型转换(面试题)
- 并行编译 Xoreax IncrediBuild