Java 如何创建文件并写入?
最简单的方法是什么?请注意,下面的每个代码示例都可能抛出Java 如何创建文件并写入?,java,file-io,Java,File Io,最简单的方法是什么?请注意,下面的每个代码示例都可能抛出IOException。为简洁起见,省略了Try/catch/finally块。有关异常处理的信息,请参阅 请注意,如果文件已经存在,下面的每个代码示例都将覆盖该文件 创建文本文件: PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8"); writer.println("The first line"); writer.println("The second l
IOException
。为简洁起见,省略了Try/catch/finally块。有关异常处理的信息,请参阅
请注意,如果文件已经存在,下面的每个代码示例都将覆盖该文件
创建文本文件:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
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
创建二进制文件:
byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();
byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
Java 7+用户可以使用该类写入文件:
创建文本文件:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
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
在Java 7及更高版本中:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"))) {
writer.write("something");
}
不过,有一些有用的实用程序:
- 来自commons io
- 番石榴
文件编写器
,但它使用默认编码,这通常不是一个好主意-最好明确指定编码
下面是Java 7之前的原始答案
另请参见:(包括NIO2)。如果您希望获得相对无痛的体验,也可以查看,更具体地说是 永远不要忘记检查第三方库。对于日期操作、常见字符串操作等,可以使代码更具可读性
Java是一种很棒的语言,但标准库有时有点低级。功能强大,但级别较低。如果出于某种原因想将创建和编写分离开来,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()
执行存在性检查并以原子方式创建文件。例如,如果您想在写入文件之前确保自己是该文件的创建者,这将非常有用。下面是一个创建或覆盖文件的小示例程序。这是一个很长的版本,因此更容易理解
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();
}
}
使用:
使用try()
将自动关闭流。此版本简短、快速(缓冲),支持选择编码
这个特性是在Java7中引入的 如果您已经有了要写入文件的内容(而不是动态生成的内容),那么在Java 7中添加作为本机I/O的一部分,可以提供实现目标的最简单、最有效的方法 基本上,创建和写入文件只需一行,而且一个简单的方法调用 以下示例创建并写入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();
}
Charset utf8=StandardCharsets.UTF_8;
列表行=数组。asList(“第1行”、“第2行”);
字节[]数据={1,2,3,4,5};
试一试{
Files.write(path.get(“file1.bin”)、数据);
Files.write(path.get(“file2.bin”)、数据、,
StandardOpenOption.CREATE、StandardOpenOption.APPEND);
write(path.get(“file3.txt”),“content.getBytes());
Files.write(path.get(“file4.txt”),“content.getBytes(utf8));
file.write(path.get(“file5.txt”),行,utf8);
file.write(path.get(“file6.txt”)、行、utf8、,
StandardOpenOption.CREATE、StandardOpenOption.APPEND);
}捕获(IOE异常){
e、 printStackTrace();
}
这里我们将在文本文件中输入一个字符串:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
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
我们可以轻松创建新文件并向其中添加内容。要在不覆盖现有文件的情况下创建文件:
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
}
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(data);
writer.close();
}
使用:
我能找到的最简单的方法是:
Path sampleOutputPath = Paths.get("/tmp/testfile")
try (BufferedWriter writer = Files.newBufferedWriter(sampleOutputPath)) {
writer.write("Hello, world!");
}
它可能只适用于1.7+。使用输入和输出流读取和写入文件:
//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");
}
}
}
//由Anurag Goel编写
//读写文件
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
公共类写文件{
公共静态void main(字符串参数[]){
试一试{
字节数组[]={'1','a','2','b','5'};
OutputStream os=新文件OutputStream(“test.txt”);
对于(int x=0;x
仅一行!
path
和line
是字符串
import java.nio.file.Files;
import java.nio.file.Paths;
Files.write(Paths.get(path), lines.getBytes());
我认为这是最短的方法:
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();
只需包含此软件包:
java.nio.file
然后您可以使用以下代码编写文件:
Path file = ...;
byte[] buf = ...;
Files.write(file, buf);
由于作者没有说明他们是否需要已下线的Java版本的解决方案(由Sun和IBM提供,这些都是技术上最广泛使用的JVM),并且由于大多数人似乎在指定它是文本(非二进制)文件之前已经回答了作者的问题,我决定提供我的答案
首先,Java6通常已经到了生命的尽头,由于作者没有指定他需要遗留兼容性,我猜它自动意味着Java7或更高版本(Java7还没有被IBM淘汰)。因此,我们可以查看文件I/O教程: 在JavaSE7发布之前,Java.io.File类是 用于文件I/O的机制,但它有几个缺点
- 许多方法在失败时都不会抛出异常,所以是这样 无法获取有用的错误消息。例如,如果一个文件 删除失败,程序将收到“删除失败”,但 不知道是不是因为文件不存在,用户不存在 有权限,或者有其他问题
- 重命名方法 跨平台工作不一致
- 没有真正的支持 用于符号链接
- 需要更多的元数据支持,例如 文件权限、文件所有者和其他安全属性。访问 文件元数据效率低下
- 许多文件方法无法扩展。
通过服务器请求大型目录列表可能会
Path file = ...; try (BufferedWriter writer = Files.newBufferedWriter(file)) { writer.append("Zero header: ").append('0').write("\r\n"); [...] }
Path file = ...; try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) { writer.write("----------"); [...] }
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"); } }
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(); } }
//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(); }
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();
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); } } }
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(); } } }
Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());
File file = new File(System.*getProperty*("java.io.tmpdir") + System.*getProperty*("file.separator") + "YourFileName.txt");
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); } }
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(); }
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(); }
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(); }
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(); }
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 } }
public void saveDataInFile(String data) throws IOException { Path path = Paths.get(fileName); byte[] strToBytes = data.getBytes(); Files.write(path, strToBytes); }
public void saveDataInFile(String data) throws IOException { RandomAccessFile stream = new RandomAccessFile(fileName, "rw"); FileChannel channel = stream.getChannel(); byte[] strBytes = data.getBytes(); ByteBuffer buffer = ByteBuffer.allocate(strBytes.length); buffer.put(strBytes); buffer.flip(); channel.write(buffer); stream.close(); channel.close(); }
public void saveDataInFile(String data) throws IOException { FileOutputStream fos = new FileOutputStream(fileName); DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos)); outStream.writeUTF(data); outStream.close(); }
public void saveDataInFile(String data) throws IOException { FileOutputStream outputStream = new FileOutputStream(fileName); byte[] strToBytes = data.getBytes(); outputStream.write(strToBytes); outputStream.close(); }
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(); }
public void saveDataInFile(String data) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(data); writer.close(); }
public void saveDataInFile(String data) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true)); writer.append(' '); writer.append(data); writer.close(); }
Path file = Paths.get("path-to-file"); byte[] buf = "text-to-write-to-file".getBytes(); Files.write(file, buf);
String s = "much-larger-text-to-write-to-file"; try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) { writer.write(s, 0, s.length()); }
Path oldFile = Paths.get("existing-file-path"); Path newFile = Paths.get("new-file-path"); try (OutputStream os = new FileOutputStream(newFile.toFile())) { Files.copy(oldFile, os); }
String s= "some-text"; FileWriter fileWriter = new FileWriter("C:\\path\\to\\file\\file.txt"); fileWriter.write(fileContent); fileWriter.close();
byte data[] = "binary-to-write-to-file".getBytes(); FileOutputStream out = new FileOutputStream("file-name"); out.write(data); out.close();