【发布时间】:2010-11-06 09:51:30
【问题描述】:
在 Java 中,我在名为“text”的字符串变量中的文本字段中有文本。
如何将“text”变量的内容保存到文件中?
【问题讨论】:
标签: java file file-io text-files
在 Java 中,我在名为“text”的字符串变量中的文本字段中有文本。
如何将“text”变量的内容保存到文件中?
【问题讨论】:
标签: java file file-io text-files
如果您只是输出文本,而不是任何二进制数据,则可以使用以下方法:
PrintWriter out = new PrintWriter("filename.txt");
然后,将您的字符串写入它,就像您对任何输出流一样:
out.println(text);
您将一如既往地需要异常处理。写完后请务必致电out.close()。
如果您使用的是 Java 7 或更高版本,您可以使用“try-with-resources statement”,它会在您完成后自动关闭您的PrintStream(即退出块),如下所示:
try (PrintWriter out = new PrintWriter("filename.txt")) {
out.println(text);
}
您仍然需要像以前一样显式抛出 java.io.FileNotFoundException。
【讨论】:
Apache Commons IO 包含一些很好的方法,特别是 FileUtils 包含以下方法:
static void writeStringToFile(File file, String data)
允许您在一个方法调用中将文本写入文件:
FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
您可能还需要考虑指定文件的编码。
【讨论】:
FileUtils.writeStringToFile(new File("test.txt"), "Hello File", forName("UTF-8"));
在 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
【讨论】:
content.getBytes(StandardCharsets.UTF_8) 可用于明确定义编码。
一个简单的例子:
try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
out.print(text);
}
【讨论】:
@Cleanup new FileOutputStream(...) 即可。
刚刚在我的项目中做了类似的事情。使用FileWriter 将简化您的部分工作。在这里你可以找到不错的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)
{
}
}
【讨论】:
write() 调用中写出整个文件时,将 FileWriter 包装在 BufferedWriter 中是多余的。
.close() 不会抛出(至少在Java 7 中?),最后的trycatch 可能是多余的吗?
throw new RuntimeException(e);
使用Apache Commons IO 中的FileUtils.writeStringToFile()。无需重新发明这个特定的轮子。
【讨论】:
在 Java 11 中,java.nio.file.Files 类被两个新的实用方法扩展以将字符串写入文件。第一种方法(参见 JavaDoc here)默认使用字符集 UTF-8:
Files.writeString(Path.of("my", "path"), "My String");
第二种方法(参见 JavaDoc here)允许指定一个单独的字符集:
Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);
这两种方法都有一个可选的 Varargs 参数,用于设置文件处理选项(参见 JavaDoc here)。以下示例将创建一个不存在的文件或将字符串附加到现有文件:
Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
【讨论】:
您可以使用修改下面的代码从处理文本的任何类或函数中写入文件。有人想知道为什么世界需要一个新的文本编辑器......
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)。上面推荐了一些库,但我最喜欢这种东西的是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
}
【讨论】:
Charsets.UTF-8。
Charsets.UTF_8
Files.asCharSink(file, charset).write(text)
使用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);
}
【讨论】:
Files.write(targetPath, bytes); 覆盖文件。它将按预期工作。
使用 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>
【讨论】:
用这个,可读性很强:
import java.nio.file.Files;
import java.nio.file.Paths;
Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);
【讨论】:
如果您需要基于单个字符串创建文本文件:
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();
}
}
}
【讨论】:
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 关键字将该类更改为 static。无论哪种方式,您都需要导入 java.io.* 以使其工作,否则将无法识别 File、FileWriter 和 BufferedWriter。
【讨论】:
你可以这样做:
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 ;
}
};
【讨论】:
使用 org.apache.commons.io.FileUtils:
FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());
【讨论】:
如果您只关心将一个文本块推送到文件,则每次都会覆盖它。
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
}
}
}
此示例允许用户使用文件选择器选择文件。
【讨论】:
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);
}
}
【讨论】:
最好在 finally 块中关闭 writer/outputstream,以防万一
finally{
if(writer != null){
try{
writer.flush();
writer.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
【讨论】:
与as here 的答案基本相同,但易于复制/粘贴,而且可以正常工作;-)
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);
}
}
【讨论】:
我认为最好的方法是使用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:
将文本行写入文件。每行都是一个字符序列,并且是 按顺序写入文件,每一行都由 平台的行分隔符,由系统属性定义 行分隔符。使用指定的字符将字符编码为字节 字符集。
options 参数指定文件的创建或打开方式。 如果不存在任何选项,则此方法就像 CREATE 一样工作, 存在 TRUNCATE_EXISTING 和 WRITE 选项。换句话说,它 打开文件进行写入,如果文件不存在则创建文件,或者 最初将现有的常规文件截断为 0 的大小。 方法确保在所有行都已关闭时关闭文件 写入(或抛出 I/O 错误或其他运行时异常)。如果 发生 I/O 错误,然后它可能会在文件创建后这样做或 被截断,或者在一些字节被写入文件之后。
请注意。我看到人们已经回答了 Java 的内置 Files.write,但我的回答有什么特别之处,似乎没人提到的是该方法的重载版本,它采用 CharSequence 的 Iterable(即字符串),而不是 byte[]数组,因此不需要text.getBytes(),我认为这有点干净。
【讨论】:
如果您希望将字符串中的回车符保存到文件中 这是一个代码示例:
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);
}
});
【讨论】:
由于在所有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;
}
【讨论】: