What's the simplest way to create and write to a (text) file in Java?
在Java中创建和写入(文本)文件的最简单方法是什么?
29 个解决方案
#1
1388
Note that each of the code samples below may throw IOException
. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.
注意,下面的每个代码示例都可能抛出IOException。Try/catch/finally块被省略了。有关异常处理的信息,请参阅本教程。
Creating a text file (note that this will overwrite the file if it already exists):
创建一个文本文件(注意,如果文件已经存在,它将覆盖该文件):
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Creating a binary file (this will also overwrite the file):
创建一个二进制文件(这也会覆盖文件):
byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();
Java 7+ users can use the Files
class to write to files:
Java 7+用户可以使用文件类来写入文件:
Creating a text file:
创建一个文本文件:
List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
//Files.write(file, lines, Charset.forName("UTF-8"), StandardOpenOption.APPEND);
Creating a binary file:
创建一个二进制文件:
byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
#2
345
In Java 7 and up:
在Java 7和up:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"))) {
writer.write("something");
}
There are useful utilities for that though:
有一些有用的实用工具:
- FileUtils.writeStringtoFile(..) from commons-io
- 从commons-io FileUtils.writeStringtoFile(. .)
- Files.write(..) from guava
- 从番石榴Files.write(. .)
Note also that you can use a FileWriter
, but it uses the default encoding, which is often a bad idea - it's best to specify the encoding explicitly.
还要注意,您可以使用FileWriter,但是它使用默认编码,这通常是一个坏主意——最好明确地指定编码。
Below is the original, prior-to-Java 7 answer
下面是原始的,原始到java 7的答案。
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"));
writer.write("Something");
} catch (IOException ex) {
// Report
} finally {
try {writer.close();} catch (Exception ex) {/*ignore*/}
}
See also: Reading, Writing, and Creating Files (includes NIO2).
参见:读取、写入和创建文件(包括NIO2)。
#3
114
If you already have the content you want to write to the file (and not generated on the fly), the java.nio.file.Files
addition in Java 7 as part of native I/O provides the simplest and most efficient way to achieve your goals.
如果您已经有了想要写入文件的内容(而不是在苍蝇上生成),那么java.nio.file。在Java 7中添加文件作为原生I/O的一部分提供了实现目标的最简单和最有效的方法。
Basically creating and writing to a file is one line only, moreover one simple method call!
基本上创建和写入文件只有一行,而且一个简单的方法调用!
The following example creates and writes to 6 different files to showcase how it can be used:
下面的示例创建并写入了6个不同的文件,以展示如何使用它:
Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("1st line", "2nd line");
byte[] data = {1, 2, 3, 4, 5};
try {
Files.write(Paths.get("file1.bin"), data);
Files.write(Paths.get("file2.bin"), data,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Files.write(Paths.get("file3.txt"), "content".getBytes());
Files.write(Paths.get("file4.txt"), "content".getBytes(utf8));
Files.write(Paths.get("file5.txt"), lines, utf8);
Files.write(Paths.get("file6.txt"), lines, utf8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
#4
68
public class Program {
public static void main(String[] args) {
String text = "Hello world";
BufferedWriter output = null;
try {
File file = new File("example.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
output.close();
}
}
}
}
#5
39
Here's a little example program to create or overwrite a file. It's the long version so it can be understood more easily.
下面是一个创建或覆盖文件的示例程序。这是很长的版本,所以更容易理解。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class writer {
public void writing() {
try {
//Whatever the file path is.
File statText = new File("E:/Java/Reference/bin/images/statsTest.txt");
FileOutputStream is = new FileOutputStream(statText);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write("POTATO!!!");
w.close();
} catch (IOException e) {
System.err.println("Problem writing to the file statsTest.txt");
}
}
public static void main(String[]args) {
writer write = new writer();
write.writing();
}
}
#6
30
Use:
使用:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) {
writer.write("text to write");
}
catch (IOException ex) {
// Handle me
}
Using try()
will close stream automatically. This version is short, fast (buffered) and enables choosing encoding.
使用try()将自动关闭流。这个版本简短,快速(缓冲),并允许选择编码。
This feature was introduced in Java 7.
这个特性是在Java 7中引入的。
#7
28
A very simple way to create and write to a file in Java:
创建和写入Java文件的一种非常简单的方法:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class CreateFiles {
public static void main(String[] args) {
try{
// Create new file
String content = "This is the content to write into create file";
String path="D:\\a\\hi.txt";
File file = new File(path);
// If file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// Write in file
bw.write(content);
// Close connection
bw.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Reference: File create Example in java
引用:在java中创建实例。
#8
16
Here we are entering a string into a text file:
这里我们将一个字符串输入到文本文件中:
String content = "This is the content to write into a file";
File file = new File("filename.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close(); // Be sure to close BufferedWriter
We can easily create a new file and add content into it.
我们可以轻松地创建一个新文件并将内容添加到其中。
#9
15
If you wish to have a relatively pain-free experience you can also have a look at the Apache Commons IO package, more specifically the FileUtils
class.
如果您希望有一个相对无痛苦的体验,您还可以查看Apache Commons IO包,更具体地说,是FileUtils类。
Never forget to check third-party libraries. Joda-Time for date manipulation, Apache Commons Lang StringUtils
for common string operations and such can make your code more readable.
永远不要忘记检查第三方库。Joda-Time的操作,Apache Commons Lang StringUtils用于普通的字符串操作,这样可以使您的代码更具可读性。
Java is a great language, but the standard library is sometimes a bit low-level. Powerful, but low-level nonetheless.
Java是一种很棒的语言,但是标准库有时有点低级。强大,但低级。
#10
10
Since the author did not specify whether they require a solution for Java versions that have been EoL'd (by both Sun and IBM, and these are technically the most widespread JVMs), and due to the fact that most people seem to have answered the author's question before it was specified that it is a text (non-binary) file, I have decided to provide my answer.
因为作者没有说明是否需要Java解决方案版本,终点会(太阳和IBM,和这些技术最广泛的jvm),,因为大多数人似乎已经回答了作者的问题之前指定这是一个文本文件(非二进制),我已决定提供我的答案。
First of all, Java 6 has generally reached end of life, and since the author did not specify he needs legacy compatibility, I guess it automatically means Java 7 or above (Java 7 is not yet EoL'd by IBM). So, we can look right at the file I/O tutorial: https://docs.oracle.com/javase/tutorial/essential/io/legacy.html
首先,Java 6已经达到了生命的极限,而且由于作者没有指定他需要遗留兼容性,我想它自动意味着Java 7或以上(Java 7还不是IBM的EoL)。因此,我们可以查看文件I/O教程:https://docs.oracle.com/javase/tutorial/essential/io/legacy.html。
Prior to the Java SE 7 release, the java.io.File class was the mechanism used for file I/O, but it had several drawbacks.
在Java SE 7发布之前,Java .io。文件类是用于文件I/O的机制,但它有几个缺点。
- Many methods didn't throw exceptions when they failed, so it was impossible to obtain a useful error message. For example, if a file deletion failed, the program would receive a "delete fail" but wouldn't know if it was because the file didn't exist, the user didn't have permissions, or there was some other problem.
- 许多方法在失败时并没有抛出异常,因此不可能获得有用的错误消息。例如,如果一个文件删除失败,程序将接收一个“删除失败”,但不知道是否是因为文件不存在,用户没有权限,或者还有其他问题。
- The rename method didn't work consistently across platforms.
- 重命名方法在不同的平台上并不一致。
- There was no real support for symbolic links.
- 对符号链接没有真正的支持。
- More support for metadata was desired, such as file permissions, file owner, and other security attributes. Accessing file metadata was inefficient.
- 需要更多的元数据支持,比如文件权限、文件所有者和其他安全属性。访问文件元数据是低效的。
- Many of the File methods didn't scale. Requesting a large directory listing over a server could result in a hang. Large directories could also cause memory resource problems, resulting in a denial of service.
- 许多文件方法都没有扩展。请求服务器上的大型目录列表可能会导致挂起。大目录也可能导致内存资源问题,从而导致拒绝服务。
- It was not possible to write reliable code that could recursively walk a file tree and respond appropriately if there were circular symbolic links.
- 不可能编写可靠的代码,可以递归地遍历文件树,并在出现循环符号链接时做出适当的响应。
Oh well, that rules out java.io.File. If a file cannot be written/appended, you may not be able to even know why.
好吧,这就排除了java。如果一个文件不能写/附加,你可能无法知道为什么。
We can continue looking at the tutorial: https://docs.oracle.com/javase/tutorial/essential/io/file.html#common
我们可以继续查看教程:https://docs.oracle.com/javase/tutorial/essential/io/file.html#common。
If you have all lines you will write (append) to the text file in advance, the recommended approach is https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java.lang.Iterable-java.nio.charset.Charset-java.nio.file.OpenOption...-
如果您已经有了所有的行,那么您将在前面的文本文件中写入(追加),推荐的方法是https://docs.oracle.com/javase/8/docs/api/java/nio/file/file/files.html #write- java.l . path -java.lang. iterable -java.n .charset - java.nio.file.openoption…
Here's an example (simplified):
这里有一个例子(简体):
Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, StandardCharsets.UTF_8);
Another example (append):
另一个例子(附加):
Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE);
If you want to write file content as you go: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newBufferedWriter-java.nio.file.Path-java.nio.charset.Charset-java.nio.file.OpenOption...-
如果你想写文件内容,你可以去:https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html# newbufferedwriter - java.nio.file.charset - java.nio.file.openoption…
Simplified example (Java 8 or up):
简化示例(Java 8或up):
Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file)) {
writer.append("Zero header: ").append('0').write("\r\n");
[...]
}
Another example (append):
另一个例子(附加):
Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
writer.write("----------");
[...]
}
These methods require minimal effort on the author's part and should be preferred to all others when writing to [text] files.
这些方法只需要对作者的部分进行最小的努力,并且在写入[文本]文件时应该优先考虑所有其他方法。
#11
9
Use:
使用:
JFileChooser c = new JFileChooser();
c.showOpenDialog(c);
File writeFile = c.getSelectedFile();
String content = "Input the data here to be written to your file";
try {
FileWriter fw = new FileWriter(writeFile);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(content);
bw.append("hiiiii");
bw.close();
fw.close();
}
catch (Exception exc) {
System.out.println(exc);
}
#12
8
I think this is the shortest way:
我认为这是最短的方法:
FileWriter fr = new FileWriter("your_file_name.txt"); // After '.' write
// your file extention (".txt" in this case)
fr.write("Things you want to write into the file"); // Warning: this will REPLACE your old file content!
fr.close();
#13
7
If you for some reason want to separate the act of creating and writing, the Java equivalent of touch
is
如果您出于某种原因想要分离创建和写入的行为,那么Java的touch就是。
try {
//create a file named "testfile.txt" in the current working directory
File myFile = new File("testfile.txt");
if ( myFile.createNewFile() ) {
System.out.println("Success!");
} else {
System.out.println("Failure!");
}
} catch ( IOException ioe ) { ioe.printStackTrace(); }
createNewFile()
does an existence check and file create atomically. This can be useful if you want to ensure you were the creator of the file before writing to it, for example.
createNewFile()执行存在检查和文件创建的原子性。例如,如果您希望确保在写入文件之前是该文件的创建者,那么这将非常有用。
#14
7
To create file without overwriting existing file:
在不覆盖现有文件的情况下创建文件:
System.out.println("Choose folder to create file");
JFileChooser c = new JFileChooser();
c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
c.showOpenDialog(c);
c.getSelectedFile();
f = c.getSelectedFile(); // File f - global variable
String newfile = f + "\\hi.doc";//.txt or .doc or .html
File file = new File(newfile);
try {
//System.out.println(f);
boolean flag = file.createNewFile();
if(flag == true) {
JOptionPane.showMessageDialog(rootPane, "File created successfully");
}
else {
JOptionPane.showMessageDialog(rootPane, "File already exists");
}
/* Or use exists() function as follows:
if(file.exists() == true) {
JOptionPane.showMessageDialog(rootPane, "File already exists");
}
else {
JOptionPane.showMessageDialog(rootPane, "File created successfully");
}
*/
}
catch(Exception e) {
// Any exception handling method of your choice
}
#15
6
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterExample {
public static void main(String [] args) {
FileWriter fw= null;
File file =null;
try {
file=new File("WriteFile.txt");
if(!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file);
fw.write("This is an string written to a file");
fw.flush();
fw.close();
System.out.println("File written Succesfully");
} catch (IOException e) {
e.printStackTrace();
}
}
}
#16
6
package fileoperations;
import java.io.File;
import java.io.IOException;
public class SimpleFile {
public static void main(String[] args) throws IOException {
File file =new File("text.txt");
file.createNewFile();
System.out.println("File is created");
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("Enter the text that you want to write");
writer.flush();
writer.close();
System.out.println("Data is entered into file");
}
}
#17
5
One line only ! path
and line
are Strings
一行只!路径和行是字符串。
import java.nio.file.Files;
import java.nio.file.Paths;
Files.write(Paths.get(path), lines.getBytes());
#18
5
The simplest way I can find:
我能找到的最简单的方法是:
Path sampleOutputPath = Paths.get("/tmp/testfile")
try (BufferedWriter writer = Files.newBufferedWriter(sampleOutputPath)) {
writer.write("Hello, world!");
}
It will probably only work for 1.7+.
它可能只适用于1.7+。
#19
4
If we are using Java 7 and above and also know the content to be added (appended) to the file we can make use of newBufferedWriter method in NIO package.
如果我们使用Java 7和以上,并且知道要添加的内容(附加到文件),我们可以在NIO包中使用newBufferedWriter方法。
public static void main(String[] args) {
Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
String text = "\n Welcome to Java 8";
//Writing to the file temp.txt
try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
writer.write(text);
} catch (IOException e) {
e.printStackTrace();
}
}
There are few points to note:
有几点需要注意:
- It is always a good habit to specify charset encoding and for that we have constant in class
StandardCharsets
. - 指定字符集编码一直是一个好习惯,并且我们在类标准字符集中有常量。
- The code uses
try-with-resource
statement in which resources are automatically closed after the try. - 代码使用try- resource语句,其中资源在尝试之后自动关闭。
Though OP has not asked but just in case we want to search for lines having some specific keyword e.g. confidential
we can make use of stream APIs in Java:
虽然OP没有要求,但只是为了以防我们想要搜索一些有特定关键字的行,例如,我们可以在Java中使用流api:
//Reading from the file the first line which contains word "confidential"
try {
Stream<String> lines = Files.lines(FILE_PATH);
Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
if(containsJava.isPresent()){
System.out.println(containsJava.get());
}
} catch (IOException e) {
e.printStackTrace();
}
#20
4
File reading and writing using input and outputstream:
使用输入和输出流的文件读取和写入:
//Coded By Anurag Goel
//Reading And Writing Files
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class WriteAFile {
public static void main(String args[]) {
try {
byte array [] = {'1','a','2','b','5'};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < array.length ; x++) {
os.write( array[x] ); // Writes the bytes
}
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for(int i=0; i< size; i++) {
System.out.print((char)is.read() + " ");
}
is.close();
} catch(IOException e) {
System.out.print("Exception");
}
}
}
#21
4
Just include this package:
包括这个包:
java.nio.file
And then you can use this code to write the file:
然后你可以用这个代码来写文件:
Path file = ...;
byte[] buf = ...;
Files.write(file, buf);
#22
3
There are some simple ways, like:
有一些简单的方法,比如:
File file = new File("filename.txt");
PrintWriter pw = new PrintWriter(file);
pw.write("The world I'm coming");
pw.close();
String write = "Hello World!";
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
fw.write(write);
fw.close();
#23
3
It's worth a try for Java 7+:
值得一试,Java 7+:
Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());
It looks promising...
它看起来有前途……
#24
3
For multiple files you can use:
对于多个文件,您可以使用:
static void out(String[] name, String[] content) {
File path = new File(System.getProperty("user.dir") + File.separator + "OUT");
for (File file : path.listFiles())
if (!file.isDirectory())
file.delete();
path.mkdirs();
File c;
for (int i = 0; i != name.length; i++) {
c = new File(path + File.separator + name[i] + ".txt");
try {
c.createNewFile();
FileWriter fiWi = new FileWriter(c.getAbsoluteFile());
BufferedWriter buWi = new BufferedWriter(fiWi);
buWi.write(content[i]);
buWi.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
It's working great.
这是伟大的工作。
#25
2
Using Google's Guava library, we can create and write to a file very easily.
使用谷歌的Guava库,我们可以很容易地创建和写入文件。
package com.zetcode.writetofileex;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
public class WriteToFileEx {
public static void main(String[] args) throws IOException {
String fileName = "fruits.txt";
File file = new File(fileName);
String content = "banana, orange, lemon, apple, plum";
Files.write(content.getBytes(), file);
}
}
The example creates a new fruits.txt
file in the project root directory.
这个例子创造了一个新的水果。txt文件在项目根目录。
#26
2
You can even create a temporary file using a system property, which will be independent of which OS you are using.
您甚至可以使用系统属性创建临时文件,该文件将独立于您正在使用的操作系统。
File file = new File(System.*getProperty*("java.io.tmpdir") +
System.*getProperty*("file.separator") +
"YourFileName.txt");
#27
1
Reading collection with customers and saving to file, with JFilechooser.
与客户一起阅读收集和保存文件,使用JFilechooser。
private void writeFile(){
JFileChooser fileChooser = new JFileChooser(this.PATH);
int retValue = fileChooser.showDialog(this, "Save File");
if (retValue == JFileChooser.APPROVE_OPTION){
try (Writer fileWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileChooser.getSelectedFile())))){
this.customers.forEach((c) ->{
try{
fileWrite.append(c.toString()).append("\n");
}
catch (IOException ex){
ex.printStackTrace();
}
});
}
catch (IOException e){
e.printStackTrace();
}
}
}
#28
1
Here are some of the possible ways to create and write a file in Java :
下面是一些在Java中创建和编写文件的方法:
Using FileOutputStream
使用FileOutputStream
try {
File fout = new File("myOutFile.txt");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("Write somthing to the file ...");
bw.newLine();
bw.close();
} catch (FileNotFoundException e){
// File was not found
e.printStackTrace();
} catch (IOException e) {
// Problem when writing to the file
e.printStackTrace();
}
Using FileWriter
使用FileWriter
try {
FileWriter fw = new FileWriter("myOutFile.txt");
fw.write("Example of content");
fw.close();
} catch (FileNotFoundException e) {
// File not found
e.printStackTrace();
} catch (IOException e) {
// Error when writing to the file
e.printStackTrace();
}
Using PrintWriter
使用PrintWriter
try {
PrintWriter pw = new PrintWriter("myOutFile.txt");
pw.write("Example of content");
pw.close();
} catch (FileNotFoundException e) {
// File not found
e.printStackTrace();
} catch (IOException e) {
// Error when writing to the file
e.printStackTrace();
}
Using OutputStreamWriter
使用OutputStreamWriter
try {
File fout = new File("myOutFile.txt");
FileOutputStream fos = new FileOutputStream(fout);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write("Soe content ...");
osw.close();
} catch (FileNotFoundException e) {
// File not found
e.printStackTrace();
} catch (IOException e) {
// Error when writing to the file
e.printStackTrace();
}
For further check this tutorial about How to read and write files in Java .
有关如何在Java中读取和写入文件,请参阅本教程。
#29
-2
Creating a sample file:
创建一个示例文件:
try {
File file = new File ("c:/new-file.txt");
if(file.createNewFile()) {
System.out.println("Successful created!");
}
else {
System.out.println("Failed to create!");
}
}
catch (IOException e) {
e.printStackTrace();
}
#1
1388
Note that each of the code samples below may throw IOException
. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.
注意,下面的每个代码示例都可能抛出IOException。Try/catch/finally块被省略了。有关异常处理的信息,请参阅本教程。
Creating a text file (note that this will overwrite the file if it already exists):
创建一个文本文件(注意,如果文件已经存在,它将覆盖该文件):
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Creating a binary file (this will also overwrite the file):
创建一个二进制文件(这也会覆盖文件):
byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();
Java 7+ users can use the Files
class to write to files:
Java 7+用户可以使用文件类来写入文件:
Creating a text file:
创建一个文本文件:
List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
//Files.write(file, lines, Charset.forName("UTF-8"), StandardOpenOption.APPEND);
Creating a binary file:
创建一个二进制文件:
byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
#2
345
In Java 7 and up:
在Java 7和up:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"))) {
writer.write("something");
}
There are useful utilities for that though:
有一些有用的实用工具:
- FileUtils.writeStringtoFile(..) from commons-io
- 从commons-io FileUtils.writeStringtoFile(. .)
- Files.write(..) from guava
- 从番石榴Files.write(. .)
Note also that you can use a FileWriter
, but it uses the default encoding, which is often a bad idea - it's best to specify the encoding explicitly.
还要注意,您可以使用FileWriter,但是它使用默认编码,这通常是一个坏主意——最好明确地指定编码。
Below is the original, prior-to-Java 7 answer
下面是原始的,原始到java 7的答案。
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"));
writer.write("Something");
} catch (IOException ex) {
// Report
} finally {
try {writer.close();} catch (Exception ex) {/*ignore*/}
}
See also: Reading, Writing, and Creating Files (includes NIO2).
参见:读取、写入和创建文件(包括NIO2)。
#3
114
If you already have the content you want to write to the file (and not generated on the fly), the java.nio.file.Files
addition in Java 7 as part of native I/O provides the simplest and most efficient way to achieve your goals.
如果您已经有了想要写入文件的内容(而不是在苍蝇上生成),那么java.nio.file。在Java 7中添加文件作为原生I/O的一部分提供了实现目标的最简单和最有效的方法。
Basically creating and writing to a file is one line only, moreover one simple method call!
基本上创建和写入文件只有一行,而且一个简单的方法调用!
The following example creates and writes to 6 different files to showcase how it can be used:
下面的示例创建并写入了6个不同的文件,以展示如何使用它:
Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("1st line", "2nd line");
byte[] data = {1, 2, 3, 4, 5};
try {
Files.write(Paths.get("file1.bin"), data);
Files.write(Paths.get("file2.bin"), data,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Files.write(Paths.get("file3.txt"), "content".getBytes());
Files.write(Paths.get("file4.txt"), "content".getBytes(utf8));
Files.write(Paths.get("file5.txt"), lines, utf8);
Files.write(Paths.get("file6.txt"), lines, utf8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
#4
68
public class Program {
public static void main(String[] args) {
String text = "Hello world";
BufferedWriter output = null;
try {
File file = new File("example.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
output.close();
}
}
}
}
#5
39
Here's a little example program to create or overwrite a file. It's the long version so it can be understood more easily.
下面是一个创建或覆盖文件的示例程序。这是很长的版本,所以更容易理解。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class writer {
public void writing() {
try {
//Whatever the file path is.
File statText = new File("E:/Java/Reference/bin/images/statsTest.txt");
FileOutputStream is = new FileOutputStream(statText);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write("POTATO!!!");
w.close();
} catch (IOException e) {
System.err.println("Problem writing to the file statsTest.txt");
}
}
public static void main(String[]args) {
writer write = new writer();
write.writing();
}
}
#6
30
Use:
使用:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) {
writer.write("text to write");
}
catch (IOException ex) {
// Handle me
}
Using try()
will close stream automatically. This version is short, fast (buffered) and enables choosing encoding.
使用try()将自动关闭流。这个版本简短,快速(缓冲),并允许选择编码。
This feature was introduced in Java 7.
这个特性是在Java 7中引入的。
#7
28
A very simple way to create and write to a file in Java:
创建和写入Java文件的一种非常简单的方法:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class CreateFiles {
public static void main(String[] args) {
try{
// Create new file
String content = "This is the content to write into create file";
String path="D:\\a\\hi.txt";
File file = new File(path);
// If file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// Write in file
bw.write(content);
// Close connection
bw.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Reference: File create Example in java
引用:在java中创建实例。
#8
16
Here we are entering a string into a text file:
这里我们将一个字符串输入到文本文件中:
String content = "This is the content to write into a file";
File file = new File("filename.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close(); // Be sure to close BufferedWriter
We can easily create a new file and add content into it.
我们可以轻松地创建一个新文件并将内容添加到其中。
#9
15
If you wish to have a relatively pain-free experience you can also have a look at the Apache Commons IO package, more specifically the FileUtils
class.
如果您希望有一个相对无痛苦的体验,您还可以查看Apache Commons IO包,更具体地说,是FileUtils类。
Never forget to check third-party libraries. Joda-Time for date manipulation, Apache Commons Lang StringUtils
for common string operations and such can make your code more readable.
永远不要忘记检查第三方库。Joda-Time的操作,Apache Commons Lang StringUtils用于普通的字符串操作,这样可以使您的代码更具可读性。
Java is a great language, but the standard library is sometimes a bit low-level. Powerful, but low-level nonetheless.
Java是一种很棒的语言,但是标准库有时有点低级。强大,但低级。
#10
10
Since the author did not specify whether they require a solution for Java versions that have been EoL'd (by both Sun and IBM, and these are technically the most widespread JVMs), and due to the fact that most people seem to have answered the author's question before it was specified that it is a text (non-binary) file, I have decided to provide my answer.
因为作者没有说明是否需要Java解决方案版本,终点会(太阳和IBM,和这些技术最广泛的jvm),,因为大多数人似乎已经回答了作者的问题之前指定这是一个文本文件(非二进制),我已决定提供我的答案。
First of all, Java 6 has generally reached end of life, and since the author did not specify he needs legacy compatibility, I guess it automatically means Java 7 or above (Java 7 is not yet EoL'd by IBM). So, we can look right at the file I/O tutorial: https://docs.oracle.com/javase/tutorial/essential/io/legacy.html
首先,Java 6已经达到了生命的极限,而且由于作者没有指定他需要遗留兼容性,我想它自动意味着Java 7或以上(Java 7还不是IBM的EoL)。因此,我们可以查看文件I/O教程:https://docs.oracle.com/javase/tutorial/essential/io/legacy.html。
Prior to the Java SE 7 release, the java.io.File class was the mechanism used for file I/O, but it had several drawbacks.
在Java SE 7发布之前,Java .io。文件类是用于文件I/O的机制,但它有几个缺点。
- Many methods didn't throw exceptions when they failed, so it was impossible to obtain a useful error message. For example, if a file deletion failed, the program would receive a "delete fail" but wouldn't know if it was because the file didn't exist, the user didn't have permissions, or there was some other problem.
- 许多方法在失败时并没有抛出异常,因此不可能获得有用的错误消息。例如,如果一个文件删除失败,程序将接收一个“删除失败”,但不知道是否是因为文件不存在,用户没有权限,或者还有其他问题。
- The rename method didn't work consistently across platforms.
- 重命名方法在不同的平台上并不一致。
- There was no real support for symbolic links.
- 对符号链接没有真正的支持。
- More support for metadata was desired, such as file permissions, file owner, and other security attributes. Accessing file metadata was inefficient.
- 需要更多的元数据支持,比如文件权限、文件所有者和其他安全属性。访问文件元数据是低效的。
- Many of the File methods didn't scale. Requesting a large directory listing over a server could result in a hang. Large directories could also cause memory resource problems, resulting in a denial of service.
- 许多文件方法都没有扩展。请求服务器上的大型目录列表可能会导致挂起。大目录也可能导致内存资源问题,从而导致拒绝服务。
- It was not possible to write reliable code that could recursively walk a file tree and respond appropriately if there were circular symbolic links.
- 不可能编写可靠的代码,可以递归地遍历文件树,并在出现循环符号链接时做出适当的响应。
Oh well, that rules out java.io.File. If a file cannot be written/appended, you may not be able to even know why.
好吧,这就排除了java。如果一个文件不能写/附加,你可能无法知道为什么。
We can continue looking at the tutorial: https://docs.oracle.com/javase/tutorial/essential/io/file.html#common
我们可以继续查看教程:https://docs.oracle.com/javase/tutorial/essential/io/file.html#common。
If you have all lines you will write (append) to the text file in advance, the recommended approach is https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java.lang.Iterable-java.nio.charset.Charset-java.nio.file.OpenOption...-
如果您已经有了所有的行,那么您将在前面的文本文件中写入(追加),推荐的方法是https://docs.oracle.com/javase/8/docs/api/java/nio/file/file/files.html #write- java.l . path -java.lang. iterable -java.n .charset - java.nio.file.openoption…
Here's an example (simplified):
这里有一个例子(简体):
Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, StandardCharsets.UTF_8);
Another example (append):
另一个例子(附加):
Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE);
If you want to write file content as you go: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newBufferedWriter-java.nio.file.Path-java.nio.charset.Charset-java.nio.file.OpenOption...-
如果你想写文件内容,你可以去:https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html# newbufferedwriter - java.nio.file.charset - java.nio.file.openoption…
Simplified example (Java 8 or up):
简化示例(Java 8或up):
Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file)) {
writer.append("Zero header: ").append('0').write("\r\n");
[...]
}
Another example (append):
另一个例子(附加):
Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
writer.write("----------");
[...]
}
These methods require minimal effort on the author's part and should be preferred to all others when writing to [text] files.
这些方法只需要对作者的部分进行最小的努力,并且在写入[文本]文件时应该优先考虑所有其他方法。
#11
9
Use:
使用:
JFileChooser c = new JFileChooser();
c.showOpenDialog(c);
File writeFile = c.getSelectedFile();
String content = "Input the data here to be written to your file";
try {
FileWriter fw = new FileWriter(writeFile);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(content);
bw.append("hiiiii");
bw.close();
fw.close();
}
catch (Exception exc) {
System.out.println(exc);
}
#12
8
I think this is the shortest way:
我认为这是最短的方法:
FileWriter fr = new FileWriter("your_file_name.txt"); // After '.' write
// your file extention (".txt" in this case)
fr.write("Things you want to write into the file"); // Warning: this will REPLACE your old file content!
fr.close();
#13
7
If you for some reason want to separate the act of creating and writing, the Java equivalent of touch
is
如果您出于某种原因想要分离创建和写入的行为,那么Java的touch就是。
try {
//create a file named "testfile.txt" in the current working directory
File myFile = new File("testfile.txt");
if ( myFile.createNewFile() ) {
System.out.println("Success!");
} else {
System.out.println("Failure!");
}
} catch ( IOException ioe ) { ioe.printStackTrace(); }
createNewFile()
does an existence check and file create atomically. This can be useful if you want to ensure you were the creator of the file before writing to it, for example.
createNewFile()执行存在检查和文件创建的原子性。例如,如果您希望确保在写入文件之前是该文件的创建者,那么这将非常有用。
#14
7
To create file without overwriting existing file:
在不覆盖现有文件的情况下创建文件:
System.out.println("Choose folder to create file");
JFileChooser c = new JFileChooser();
c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
c.showOpenDialog(c);
c.getSelectedFile();
f = c.getSelectedFile(); // File f - global variable
String newfile = f + "\\hi.doc";//.txt or .doc or .html
File file = new File(newfile);
try {
//System.out.println(f);
boolean flag = file.createNewFile();
if(flag == true) {
JOptionPane.showMessageDialog(rootPane, "File created successfully");
}
else {
JOptionPane.showMessageDialog(rootPane, "File already exists");
}
/* Or use exists() function as follows:
if(file.exists() == true) {
JOptionPane.showMessageDialog(rootPane, "File already exists");
}
else {
JOptionPane.showMessageDialog(rootPane, "File created successfully");
}
*/
}
catch(Exception e) {
// Any exception handling method of your choice
}
#15
6
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterExample {
public static void main(String [] args) {
FileWriter fw= null;
File file =null;
try {
file=new File("WriteFile.txt");
if(!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file);
fw.write("This is an string written to a file");
fw.flush();
fw.close();
System.out.println("File written Succesfully");
} catch (IOException e) {
e.printStackTrace();
}
}
}
#16
6
package fileoperations;
import java.io.File;
import java.io.IOException;
public class SimpleFile {
public static void main(String[] args) throws IOException {
File file =new File("text.txt");
file.createNewFile();
System.out.println("File is created");
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("Enter the text that you want to write");
writer.flush();
writer.close();
System.out.println("Data is entered into file");
}
}
#17
5
One line only ! path
and line
are Strings
一行只!路径和行是字符串。
import java.nio.file.Files;
import java.nio.file.Paths;
Files.write(Paths.get(path), lines.getBytes());
#18
5
The simplest way I can find:
我能找到的最简单的方法是:
Path sampleOutputPath = Paths.get("/tmp/testfile")
try (BufferedWriter writer = Files.newBufferedWriter(sampleOutputPath)) {
writer.write("Hello, world!");
}
It will probably only work for 1.7+.
它可能只适用于1.7+。
#19
4
If we are using Java 7 and above and also know the content to be added (appended) to the file we can make use of newBufferedWriter method in NIO package.
如果我们使用Java 7和以上,并且知道要添加的内容(附加到文件),我们可以在NIO包中使用newBufferedWriter方法。
public static void main(String[] args) {
Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
String text = "\n Welcome to Java 8";
//Writing to the file temp.txt
try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
writer.write(text);
} catch (IOException e) {
e.printStackTrace();
}
}
There are few points to note:
有几点需要注意:
- It is always a good habit to specify charset encoding and for that we have constant in class
StandardCharsets
. - 指定字符集编码一直是一个好习惯,并且我们在类标准字符集中有常量。
- The code uses
try-with-resource
statement in which resources are automatically closed after the try. - 代码使用try- resource语句,其中资源在尝试之后自动关闭。
Though OP has not asked but just in case we want to search for lines having some specific keyword e.g. confidential
we can make use of stream APIs in Java:
虽然OP没有要求,但只是为了以防我们想要搜索一些有特定关键字的行,例如,我们可以在Java中使用流api:
//Reading from the file the first line which contains word "confidential"
try {
Stream<String> lines = Files.lines(FILE_PATH);
Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
if(containsJava.isPresent()){
System.out.println(containsJava.get());
}
} catch (IOException e) {
e.printStackTrace();
}
#20
4
File reading and writing using input and outputstream:
使用输入和输出流的文件读取和写入:
//Coded By Anurag Goel
//Reading And Writing Files
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class WriteAFile {
public static void main(String args[]) {
try {
byte array [] = {'1','a','2','b','5'};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < array.length ; x++) {
os.write( array[x] ); // Writes the bytes
}
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for(int i=0; i< size; i++) {
System.out.print((char)is.read() + " ");
}
is.close();
} catch(IOException e) {
System.out.print("Exception");
}
}
}
#21
4
Just include this package:
包括这个包:
java.nio.file
And then you can use this code to write the file:
然后你可以用这个代码来写文件:
Path file = ...;
byte[] buf = ...;
Files.write(file, buf);
#22
3
There are some simple ways, like:
有一些简单的方法,比如:
File file = new File("filename.txt");
PrintWriter pw = new PrintWriter(file);
pw.write("The world I'm coming");
pw.close();
String write = "Hello World!";
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
fw.write(write);
fw.close();
#23
3
It's worth a try for Java 7+:
值得一试,Java 7+:
Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());
It looks promising...
它看起来有前途……
#24
3
For multiple files you can use:
对于多个文件,您可以使用:
static void out(String[] name, String[] content) {
File path = new File(System.getProperty("user.dir") + File.separator + "OUT");
for (File file : path.listFiles())
if (!file.isDirectory())
file.delete();
path.mkdirs();
File c;
for (int i = 0; i != name.length; i++) {
c = new File(path + File.separator + name[i] + ".txt");
try {
c.createNewFile();
FileWriter fiWi = new FileWriter(c.getAbsoluteFile());
BufferedWriter buWi = new BufferedWriter(fiWi);
buWi.write(content[i]);
buWi.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
It's working great.
这是伟大的工作。
#25
2
Using Google's Guava library, we can create and write to a file very easily.
使用谷歌的Guava库,我们可以很容易地创建和写入文件。
package com.zetcode.writetofileex;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
public class WriteToFileEx {
public static void main(String[] args) throws IOException {
String fileName = "fruits.txt";
File file = new File(fileName);
String content = "banana, orange, lemon, apple, plum";
Files.write(content.getBytes(), file);
}
}
The example creates a new fruits.txt
file in the project root directory.
这个例子创造了一个新的水果。txt文件在项目根目录。
#26
2
You can even create a temporary file using a system property, which will be independent of which OS you are using.
您甚至可以使用系统属性创建临时文件,该文件将独立于您正在使用的操作系统。
File file = new File(System.*getProperty*("java.io.tmpdir") +
System.*getProperty*("file.separator") +
"YourFileName.txt");
#27
1
Reading collection with customers and saving to file, with JFilechooser.
与客户一起阅读收集和保存文件,使用JFilechooser。
private void writeFile(){
JFileChooser fileChooser = new JFileChooser(this.PATH);
int retValue = fileChooser.showDialog(this, "Save File");
if (retValue == JFileChooser.APPROVE_OPTION){
try (Writer fileWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileChooser.getSelectedFile())))){
this.customers.forEach((c) ->{
try{
fileWrite.append(c.toString()).append("\n");
}
catch (IOException ex){
ex.printStackTrace();
}
});
}
catch (IOException e){
e.printStackTrace();
}
}
}
#28
1
Here are some of the possible ways to create and write a file in Java :
下面是一些在Java中创建和编写文件的方法:
Using FileOutputStream
使用FileOutputStream
try {
File fout = new File("myOutFile.txt");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("Write somthing to the file ...");
bw.newLine();
bw.close();
} catch (FileNotFoundException e){
// File was not found
e.printStackTrace();
} catch (IOException e) {
// Problem when writing to the file
e.printStackTrace();
}
Using FileWriter
使用FileWriter
try {
FileWriter fw = new FileWriter("myOutFile.txt");
fw.write("Example of content");
fw.close();
} catch (FileNotFoundException e) {
// File not found
e.printStackTrace();
} catch (IOException e) {
// Error when writing to the file
e.printStackTrace();
}
Using PrintWriter
使用PrintWriter
try {
PrintWriter pw = new PrintWriter("myOutFile.txt");
pw.write("Example of content");
pw.close();
} catch (FileNotFoundException e) {
// File not found
e.printStackTrace();
} catch (IOException e) {
// Error when writing to the file
e.printStackTrace();
}
Using OutputStreamWriter
使用OutputStreamWriter
try {
File fout = new File("myOutFile.txt");
FileOutputStream fos = new FileOutputStream(fout);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write("Soe content ...");
osw.close();
} catch (FileNotFoundException e) {
// File not found
e.printStackTrace();
} catch (IOException e) {
// Error when writing to the file
e.printStackTrace();
}
For further check this tutorial about How to read and write files in Java .
有关如何在Java中读取和写入文件,请参阅本教程。
#29
-2
Creating a sample file:
创建一个示例文件:
try {
File file = new File ("c:/new-file.txt");
if(file.createNewFile()) {
System.out.println("Successful created!");
}
else {
System.out.println("Failed to create!");
}
}
catch (IOException e) {
e.printStackTrace();
}