Jus*_*ite 667 java file-io file text-files
在Java中,我有一个名为"text"的String变量中的文本字段的文本.
如何将"text"变量的内容保存到文件中?
Jer*_*yth 706
如果您只是输出文本而不是任何二进制数据,则以下内容将起作用:
PrintWriter out = new PrintWriter("filename.txt");
Run Code Online (Sandbox Code Playgroud)
然后,将String写入它,就像您对任何输出流一样:
out.println(text);
Run Code Online (Sandbox Code Playgroud)
你需要像往常一样处理异常处理.out.close()写完后一定要打电话.
如果您使用的是Java 7或更高版本,则可以使用" try-with-resources语句 ",它将PrintStream在您完成时自动关闭(即退出块),如下所示:
try (PrintWriter out = new PrintWriter("filename.txt")) {
out.println(text);
}
Run Code Online (Sandbox Code Playgroud)
您仍然需要java.io.FileNotFoundException像以前一样显式抛出.
Jon*_*Jon 237
Apache Commons IO包含一些很好的方法,特别是FileUtils包含以下方法:
static void writeStringToFile(File file, String data)
Run Code Online (Sandbox Code Playgroud)
它允许您在一个方法调用中将文本写入文件:
FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
Run Code Online (Sandbox Code Playgroud)
您可能还需要考虑指定文件的编码.
Jor*_*orn 91
一个简单的例子:
try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
out.print(text);
}
Run Code Online (Sandbox Code Playgroud)
Art*_*ger 78
刚刚在我的项目中做了类似的事情.使用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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*lev 75
在Java 7中,您可以这样做:
String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());
Run Code Online (Sandbox Code Playgroud)
这里有更多信息:http: //www.drdobbs.com/jvm/java-se-7-new-file-io/231600403
ska*_*man 60
使用FileUtils.writeStringToFile()来自Apache的百科全书IO.无需重新发明这个特殊的轮子.
小智 22
您可以使用修改下面的代码从处理文本的任何类或函数中编写您的文件.人们想知道为什么世界需要一个新的文本编辑器......
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*cel 18
在Java 11中,java.nio.file.Files类通过两个新的实用程序方法进行了扩展,将字符串写入文件(请参阅此处和此处的 JavaDoc ).在最简单的情况下,它现在是一个单行:
Files.writeString(Path.of("my", "path"), "My String");
Run Code Online (Sandbox Code Playgroud)
使用可选的Varargs参数,可以设置其他选项,例如附加到现有文件或自动创建不存在的文件(请参阅此处的 JavaDoc ).
Spi*_*ina 12
我希望尽可能依赖库来进行这种操作.这使我不太可能意外地省略了一个重要的步骤(如上面的错误狼人).上面提到了一些库,但我最喜欢的是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
}
Run Code Online (Sandbox Code Playgroud)
小智 12
使用Apache Commons IO api.这很简单
使用API作为
FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");
Run Code Online (Sandbox Code Playgroud)
Maven依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
小智 12
如果您需要基于单个字符串创建文本文件:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ran*_*ler 11
使用它,它非常易读:
import java.nio.file.Files;
import java.nio.file.Paths;
Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);
Run Code Online (Sandbox Code Playgroud)
Mos*_*aei 10
你可以这样做:
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 ;
}
};
Run Code Online (Sandbox Code Playgroud)
Sea*_*ton 10
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
Run Code Online (Sandbox Code Playgroud)
您可以将此方法插入到类中.如果在具有main方法的类中使用此方法,请通过添加静态关键字将此类更改为static.无论哪种方式,您都需要导入java.io.*才能使其工作,否则将无法识别File,FileWriter和BufferedWriter.
Bul*_*aza 10
使用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);
}
Run Code Online (Sandbox Code Playgroud)
使用org.apache.commons.io.FileUtils:
FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());
Run Code Online (Sandbox Code Playgroud)
如果您只关心将一个文本块推送到文件,则每次都会覆盖它.
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
此示例允许用户使用文件选择器选择文件.
小智 6
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);
}
}
Run Code Online (Sandbox Code Playgroud)
基本上与这里的答案相同,但很容易复制/粘贴,而且它就可以工作;-)
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);
}
}
Run Code Online (Sandbox Code Playgroud)