How do I create a file and write to it in Java?
用Java创建和写入一个(文本)文件最简单的方法是什么?
注意,下面的每个代码示例都可能抛出
请注意,如果文件已经存在,下面的每个代码示例都将覆盖该文件
创建文本文件:
1 2 3 4 | PrintWriter writer = new PrintWriter("the-file-name.txt","UTF-8"); writer.println("The first line"); writer.println("The second line"); writer.close(); |
创建二进制文件:
1 2 3 4 | byte data[] = ... FileOutputStream out = new FileOutputStream("the-file-name"); out.write(data); out.close(); |
Java 7 +用户可以使用EDCOX1×1的类来写入文件:
创建文本文件:
1 2 3 4 | 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); |
创建二进制文件:
1 2 3 4 | byte data[] = ... Path file = Paths.get("the-file-name"); Files.write(file, data); //Files.write(file, data, StandardOpenOption.APPEND); |
在Java 7和UP中:
1 2 3 4 | try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("filename.txt"),"utf-8"))) { writer.write("something"); } |
不过,有一些有用的实用程序:
- 来自Commons IO的fileutils.writeStringToFile(..)
- 文件。从guava写入(..)
还要注意,您可以使用
下面是原始的,在Java 7回答之前
1 2 3 4 5 6 7 8 9 10 11 | 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*/} } |
另请参见:读取、写入和创建文件(包括NIO2)。
如果您已经拥有要写入文件的内容(而不是立即生成),在Java 7中作为本地I/O的一部分添加EDCOX1×8增加了实现目标的最简单和最有效的方式。
基本上,创建和写入一个文件只是一行,而且一个简单的方法调用!
以下示例创建并写入6个不同的文件,以展示如何使用它:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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(); } } } } |
下面是一个创建或覆盖文件的小示例程序。这是一个很长的版本,所以更容易理解。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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(); } } |
用途:
1 2 3 4 5 6 | try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) { writer.write("text to write"); } catch (IOException ex) { // Handle me } |
使用
这个特性是在Java 7中引入的。
在Java中创建和写入文件的一种非常简单的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 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); } } } |
参考:文件在Java中创建示例
这里,我们在文本文件中输入一个字符串:
1 2 3 4 5 6 | 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 |
我们可以轻松地创建一个新文件并向其中添加内容。
如果您希望有一个相对轻松的体验,您还可以查看ApacheCommons IO包,更具体地说是
永远不要忘记检查第三方库。joda time用于日期操作,apache commons lang
Java是一种很好的语言,但是标准库有时有点低级。强大,但水平低。
因为作者没有指定他们是否需要一个已经被EOL的Java版本的解决方案(Sun和IBM两个,这些技术上是最广泛的JVM),并且由于大多数人在指定它是文本(非二进制)文件之前似乎已经回答了作者的问题,所以我决定提供我的。回答。
首先,Java 6一般已经达到了生命的尽头,由于作者没有指定他需要继承兼容性,所以我猜想它自动地意味着Java&Nbsp 7或以上(Java&Nbsp 7还没有IBM的EOL)。因此,我们可以直接查看文件I/O教程:https://docs.oracle.com/javase/tutorial/essential/i o/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.
- 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.
哦,那就排除了java.io.file。如果一个文件不能被写入/追加,你甚至不知道为什么。
我们可以继续查看教程:https://docs.oracle.com/javase/tutorial/essential/io/file.html_common
如果您有所有的行,您将提前写入(附加)到文本文件,建议的方法是http://DOCS.COM/JavaSe/ 8 /DOCS/API/Java/NiO/Frase/Field.html HTML编写Java.Nio.Fras.java. Lang.TyrabyJava.Nio.CabStas.CyStavajava. Nio.FieldOpenOp选项…
以下是一个示例(简化):
1 2 3 | Path file = ...; List<String> linesInMemory = ...; Files.write(file, linesInMemory, StandardCharsets.UTF_8); |
另一个示例(附加):
1 2 3 | Path file = ...; List<String> linesInMemory = ...; Files.write(file, linesInMemory, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE); |
如果要在执行过程中写入文件内容:http://DOCS.COM/JavaSe/ 8 /DOCS/API/Java/NiO/文件/文件。
简化示例(Java&Nbsp;8或UP):
1 2 3 4 5 6 7 | Path file = ...; try (BufferedWriter writer = Files.newBufferedWriter(file)) { writer.append("Zero header:").append('0').write(" "); [...] } |
另一个示例(附加):
1 2 3 4 5 | Path file = ...; try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) { writer.write("----------"); [...] } |
这些方法对作者来说需要最少的努力,并且在写入[文本]文件时应该优先于所有其他方法。
如果出于某种原因,您想分离创建和写入的行为,则EDCOX1 OR 5的Java等价物是
1 2 3 4 5 6 7 8 9 | 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(); } |
用途:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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); } |
我认为这是最短的途径:
1 2 3 4 | 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中创建和编写文件的可能方法:
使用FileOutputStream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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(); } |
使用文件编写器
1 2 3 4 5 6 7 8 9 10 11 | 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(); } |
使用打印机
1 2 3 4 5 6 7 8 9 10 11 | 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(); } |
使用OutputStreamWriter
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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(); } |
为了进一步检查本教程关于如何在Java中读取和写入文件。
要在不覆盖现有文件的情况下创建文件,请执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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 } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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(); } } } |
我能找到的最简单的方法是:
1 2 3 4 | Path sampleOutputPath = Paths.get("/tmp/testfile") try (BufferedWriter writer = Files.newBufferedWriter(sampleOutputPath)) { writer.write("Hello, world!"); } |
它可能只适用于1.7+版本。
只行一行!
1 2 3 4 | import java.nio.file.Files; import java.nio.file.Paths; Files.write(Paths.get(path), lines.getBytes()); |
最好的方法是使用Java7:Java 7引入了一种新的方法来处理文件系统,以及一个新的实用工具类——文件。使用files类,我们还可以创建、移动、复制、删除文件和目录;它还可以用于读取和写入文件。
1 2 3 4 5 6 | public void saveDataInFile(String data) throws IOException { Path path = Paths.get(fileName); byte[] strToBytes = data.getBytes(); Files.write(path, strToBytes); } |
用FileChannel写入如果您处理的是大型文件,则FileChannel可能比标准IO更快。以下代码使用filechannel将字符串写入文件:
1 2 3 4 5 6 7 8 9 10 11 12 | 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(); } |
使用DataOutputStream写入
1 2 3 4 5 6 | public void saveDataInFile(String data) throws IOException { FileOutputStream fos = new FileOutputStream(fileName); DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos)); outStream.writeUTF(data); outStream.close(); } |
使用FileOutputStream写入
现在我们来看看如何使用fileoutputstream将二进制数据写入文件。以下代码转换字符串int字节,并使用fileoutputstream将字节写入文件:
1 2 3 4 5 6 7 | public void saveDataInFile(String data) throws IOException { FileOutputStream outputStream = new FileOutputStream(fileName); byte[] strToBytes = data.getBytes(); outputStream.write(strToBytes); outputStream.close(); } |
使用PrintWriter编写我们可以使用打印机将格式化文本写入文件:
1 2 3 4 5 6 7 | 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(); } |
使用BufferedWriter写入:使用BufferedWriter将字符串写入新文件:
1 2 3 4 5 6 | public void saveDataInFile(String data) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(data); writer.close(); } |
将字符串附加到现有文件:
1 2 3 4 5 6 7 | public void saveDataInFile(String data) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true)); writer.append(' '); writer.append(data); writer.close(); } |
只包括这个包:
1 | java.nio.file |
然后您可以使用此代码编写文件:
1 2 3 | Path file = ...; byte[] buf = ...; Files.write(file, buf); |
如果我们使用Java 7和以上,并且知道要添加到文件中的内容(附加),我们可以在NIO包中使用NeXBuffReDeRead方法。
1 2 3 4 5 6 7 8 9 10 11 12 | public static void main(String[] args) { Path FILE_PATH = Paths.get("C:/temp","temp.txt"); String text =" 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(); } } |
有几点需要注意:
虽然OP并没有要求,但是如果我们想搜索具有特定关键字的行,例如EDCOX1,2,那么我们可以在Java中使用流API。
1 2 3 4 5 6 7 8 9 10 | //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(); } |
值得一试的Java 7 +:
1 | Files.write(Paths.get("./output.txt"),"Information string herer".getBytes()); |
看起来很有希望…
使用输入和输出流读取和写入文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | //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"); } } } |
有一些简单的方法,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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(); |
甚至可以使用系统属性创建临时文件,该属性与您使用的操作系统无关。
1 2 3 |
在Java 8中使用文件和路径并使用尝试资源构建。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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 "); writer.write("Python "); writer.write("Clojure "); writer.write("Scala "); writer.write("JavaScript "); } // the file will be automatically closed } } |
使用jFileChooser与客户一起读取集合并保存到文件中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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(" "); } catch (IOException ex){ ex.printStackTrace(); } }); } catch (IOException e){ e.printStackTrace(); } } } |
使用Google的guava库,我们可以创建和写入一个文件,很容易。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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); } } |
该示例在项目根目录中创建一个新的
创建示例文件:
1 2 3 4 5 6 7 8 9 10 11 12 | 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(); } |