//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");
}
}
}
6
在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);
}
}
}
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();
}
}
}
6
要创建文件而不覆盖现有文件:
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
}
2
使用:
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);
}
9
以下是使用Java创建和编写文件的一些可能方法:
Using 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
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
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
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();
}
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(); }
public void saveDataInFile(String data) throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
outStream.writeUTF(data);
outStream.close();
}
Write with FileOutputStream
现在让我们看看如何使用FileOutputStream将二进制数据写入文件 . 以下代码转换String int bytes并使用FileOutputStream将字节写入文件:
public void saveDataInFile(String data) throws IOException {
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = data.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
Write with PrintWriter 我们可以使用PrintWriter将格式化文本写入文件:
public void saveDataInFile() throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Some String");
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
printWriter.close();
}
Write with BufferedWriter: 使用BufferedWriter将String写入新文件:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(data);
writer.close();
}
将String附加到现有文件:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(data);
writer.close();
}
31
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();
}
}
}
}
18
这是一个用于创建或覆盖文件的示例程序 . 它是长版本,因此可以更容易理解 .
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();
}
}
12
您甚至可以使用 system property 创建临时文件独立于您使用的操作系统 .
File file = new File(System.*getProperty*("java.io.tmpdir") +
System.*getProperty*("file.separator") +
"YourFileName.txt");
9
我认为这是最短的方式:
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();
//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();
}
4
使用:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) {
writer.write("text to write");
}
catch (IOException ex) {
// Handle me
}
使用 try() 将自动关闭流 . 此版本简短,快速(缓冲)并允许选择编码 .
此功能是在Java 7中引入的 .
4
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");
}
}
3
在Java 8中,使用文件和路径并使用try-with-resources构造 .
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class WriteFile{
public static void main(String[] args) throws IOException {
String file = "text.txt";
System.out.println("Writing to file: " + file);
// Files.newBufferedWriter() uses UTF-8 encoding by default
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(file))) {
writer.write("Java\n");
writer.write("Python\n");
writer.write("Clojure\n");
writer.write("Scala\n");
writer.write("JavaScript\n");
} // the file will be automatically closed
}
}
3
这里我们将一个字符串输入到文本文件中:
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
我们可以轻松创建新文件并在其中添加内容 .
2
有一些简单的方法,如:
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();
0
在Java 7及更高版本中:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"))) {
writer.write("something");
}
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
创建二进制文件(这也会覆盖文件):
byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();
30 回答
Java 7值得一试:
看起来很有希望......
如果您已经拥有要写入文件的内容(而不是动态生成),那么Java 7中的java.nio.file.Files添加作为本机I / O的一部分,可以提供最简单,最有效的方法来实现您的目标 .
基本上创建和写入文件只是一行,而且 one simple method call !
以下示例创建并写入6个不同的文件以展示如何使用它:
使用输入和输出流进行文件读写:
在Java中创建和写入文件的一种非常简单的方法:
参考:File create Example in java
只有一行!
path
和line
是字符串要创建文件而不覆盖现有文件:
使用:
以下是使用Java创建和编写文件的一些可能方法:
Using FileOutputStream
Using FileWriter
Using PrintWriter
Using OutputStreamWriter
有关如何read and write files in Java的进一步检查本教程 .
如果由于某种原因想要分离创建和编写的行为,那么
touch
的Java等价物就是createNewFile()
执行存在检查并以原子方式创建文件 . 例如,如果您想在写入文件之前确保自己是文件的创建者,这将非常有用 .只需包含此套餐:
然后你可以使用这段代码来编写文件:
使用JFilechooser阅读与客户的集合并保存到文件 .
创建示例文件:
由于作者没有指定在指定它是 text (non-binary) 文件之前是否需要针对EoL _330329问题的Java版本的解决方案,因此我决定提供我的答案 .
首先,Java 6通常已达到使用寿命,并且由于作者没有指定他需要遗留兼容性,我想它自动意味着Java 7或更高版本(Java 7尚未由IBM进行EoL) . 所以,我们可以正确查看文件I / O教程:https://docs.oracle.com/javase/tutorial/essential/io/legacy.html
哦,那排除了java.io.File . 如果无法写入/追加文件,您可能无法知道原因 .
我们可以继续查看教程: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 ,推荐的方法是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...-
这是一个例子(简化):
另一个例子(追加):
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...-
简化示例(Java 8或更高版本):
另一个例子(追加):
这些方法对作者来说需要的工作量很小,在写入[text]文件时应该优先于所有其他方法 .
best way is to use Java7: Java 7引入了一种使用文件系统的新方法,以及一个新的实用程序类 - Files . 使用Files类,我们也可以创建,移动,复制,删除文件和目录;它也可以用来读写文件 .
Write with FileChannel 如果您正在处理大文件,FileChannel可能比标准IO更快 . 以下代码使用FileChannel将String写入文件:
Write with DataOutputStream
Write with FileOutputStream
现在让我们看看如何使用FileOutputStream将二进制数据写入文件 . 以下代码转换String int bytes并使用FileOutputStream将字节写入文件:
Write with PrintWriter 我们可以使用PrintWriter将格式化文本写入文件:
Write with BufferedWriter: 使用BufferedWriter将String写入新文件:
将String附加到现有文件:
这是一个用于创建或覆盖文件的示例程序 . 它是长版本,因此可以更容易理解 .
您甚至可以使用 system property 创建临时文件独立于您使用的操作系统 .
我认为这是最短的方式:
使用Google的Guava库,我们可以非常轻松地创建和写入文件 .
该示例在项目根目录中创建一个新的
fruits.txt
文件 .如果您希望获得相对无痛苦的体验,您还可以查看Apache Commons IO package,更具体地说是FileUtils class .
永远不要忘记检查第三方库 . Joda-Time用于日期操作,Apache Commons Lang StringUtils用于常见的字符串操作,这样可以使您的代码更具可读性 .
Java是一种很棒的语言,但标准库有时候有点低级 . 虽然功能强大,但却很低级 .
我能找到最简单的方法:
它可能只适用于1.7 .
如果我们使用Java 7及更高版本并且还知道要添加(附加)到文件的内容,我们可以在NIO包中使用newBufferedWriter方法 .
有几点需要注意:
指定charset编码总是一个好习惯,因为我们在类
StandardCharsets
中有常量 .该代码使用
try-with-resource
语句,其中资源在尝试后自动关闭 .虽然OP没有问过,但是我们想要搜索具有某些特定关键字的行,例如
confidential
我们可以在Java中使用流API:使用:
使用
try()
将自动关闭流 . 此版本简短,快速(缓冲)并允许选择编码 .此功能是在Java 7中引入的 .
在Java 8中,使用文件和路径并使用try-with-resources构造 .
这里我们将一个字符串输入到文本文件中:
我们可以轻松创建新文件并在其中添加内容 .
有一些简单的方法,如:
在Java 7及更高版本中:
但是有一些有用的实用程序:
989 FileUtils.writeStringtoFile(..)来自commons-io
来自 Guava
另请注意,您可以使用
FileWriter
,但它使用默认编码,这通常是一个坏主意 - 最好明确指定编码 .以下是Java 7之前的原始答案
另请参阅:Reading, Writing, and Creating Files(包括NIO2) .
请注意,下面的每个代码示例都可能抛出
IOException
. 为简洁起见,省略了try / catch / finally块 . 有关异常处理的信息,请参阅this tutorial .创建一个文本文件(请注意,如果文件已经存在,这将覆盖该文件):
创建二进制文件(这也会覆盖文件):
Java 7+ 用户可以使用Files类写入文件:
创建文本文件:
创建二进制文件: