在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
当前回答
使用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.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();
}
}
}
你可以这样做:
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 ;
}
};
只是在我的项目中做了类似的事情。使用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)
{
}
}
使用这个,它非常易读:
import java.nio.file.Files;
import java.nio.file.Paths;
Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);
我认为最好的方法是使用File.write(路径路径,Iterable<?extends CharSequence>行,OpenOption…options):
String text = "content";
Path path = Paths.get("path", "to", "file");
Files.write(path, Arrays.asList(text));
参见javadoc:
将文本行写入文件。每一行都是一个字符序列按顺序写入文件,每行以平台的行分隔符,由系统属性定义line.separator。字符使用指定的字符集。options参数指定如何创建或打开文件。如果不存在任何选项,则该方法的工作方式与CREATE,存在TRUNCATE_EXISTING和WRITE选项。换句话说打开文件进行写入,如果文件不存在则创建文件,或最初将现有的常规文件截断为0的大小。这个方法确保文件在所有行都已关闭时关闭写入(或引发I/O错误或其他运行时异常)。如果如果发生I/O错误,则可能会在文件创建或或者在一些字节被写入文件之后。
请注意。我看到人们已经用Java内置的Files.write进行了回答,但我的回答中有一个特别之处,似乎没有人提到,那就是重载版本的方法,它采用了CharSequence的Iterable(即String),而不是byte[]数组,因此不需要text.getBytes(),我认为这有点干净。