What's the simplest way to create and write to a (text) file in Java?
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.
Note that each of the code samples below will overwrite the file if it already exists
Creating a text file:
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:
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:
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, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.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);
In Java 7 and 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
Files.write(..) from guava
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.
Below is the original, prior-to-Java 7 answer
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).
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.
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:
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();
}
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 ) {
try {
output.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
}
A very simple way to create and write to a file in 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);
}
}
}
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();
}
}
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.
This feature was introduced in Java 7.
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.
There are many ways of writing to a file. Each has its benefits, and each might be simplest in a given scenario.
This answer is centred on Java 8, and tries to cover all the details needed for the Java Professional Exam. Classes involved include:
.
├── OutputStream
│ └── FileOutputStream
├── Writer
│ ├── OutputStreamWriter
│ │ └── FileWriter
│ ├── BufferedWriter
│ └── PrintWriter (Java 5+)
└── Files (Java 7+)
There are 5 main ways of writing to a file:
┌───────────────────────────┬────────────────────────┬─────────────┬──────────────┐
│ │ Buffer for │ Can specify │ Throws │
│ │ large files? │ encoding? │ IOException? │
├───────────────────────────┼────────────────────────┼─────────────┼──────────────┤
│ OutputStreamWriter │ Wrap in BufferedWriter │ Y │ Y │
│ FileWriter │ Wrap in BufferedWriter │ │ Y │
│ PrintWriter │ Y │ Y │ │
│ Files.write() │ │ Y │ Y │
│ Files.newBufferedWriter() │ Y │ Y │ Y │
└───────────────────────────┴────────────────────────┴─────────────┴──────────────┘
Each has its own distinctive benefits:
OutputStreamWriter - The most basic way before Java 5
FileWriter – Optional append constructor argument
PrintWriter – Lots of methods
Files.write() – Create and write to a file in a single call
Files.newBufferedWriter() – Makes it easy to write large files
Below are details of each.
FileOutputStream
This class is meant for writing streams of raw bytes. All the Writer approaches below rely on this class, either explicitly or under the hood.
try (FileOutputStream stream = new FileOutputStream("file.txt");) {
byte data[] = "foo".getBytes();
stream.write(data);
} catch (IOException e) {}
Note that the try-with-resources statement takes care of stream.close() and that closing the stream flushes it, like stream.flush().
OutputStreamWriter
This class is a bridge from character streams to byte streams. It can wrap a FileOutputStream, and write strings:
Charset utf8 = StandardCharsets.UTF_8;
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File("file.txt")), utf8)) {
writer.write("foo");
} catch (IOException e) {}
BufferedWriter
This class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
It can wrap an OutputStreamWriter:
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("file.txt"))))) {
writer.write("foo");
writer.newLine(); // method provided by BufferedWriter
} catch (IOException e) {}
Pre Java 5 this was the best approach for large files (with a regular try/catch block).
FileWriter
This is a subclass of the OutputStreamWriter, and is a convenience class for writing character files:
boolean append = false;
try(FileWriter writer = new FileWriter("file.txt", append) ){
writer.write("foo");
writer.append("bar");
} catch (IOException e) {}
The key benefit is that it has an optional append constructor argument, which determines whether it appends to or overwrites the existing file. Note that the append/overwrite behaviour is not controlled by the write() and append() methods, which behave in nearly the same way.
Note that:
There is no buffering, but to handle large files it can be wrapped in a BufferedWriter.
FileWriter uses the default encoding. It's often preferable to specify encoding explicitly
PrintWriter
This class prints formatted representations of objects to a text-output stream. Under the hood it is the same as the BufferedWriter approach above (new BufferedWriter(new OutputStreamWriter(new FileOutputStream(...)))). PrintWriter was introduced in Java 5 as a convenient way to call this idiom, and adds additional methods such as printf() and println().
Methods in this class don't throw I/O exceptions. You can check errors by calling checkError(). The destination of a PrintWriter instance can be a File, OutputStream or Writer. Here is an example of writing to a file:
try (PrintWriter writer = new PrintWriter("file.txt", "UTF-8")) {
writer.print("foo");
writer.printf("bar %d $", "a", 1);
writer.println("baz");
} catch (FileNotFoundException e) {
} catch (UnsupportedEncodingException e) {}
When writing to an OutputStream or Writer there is an optional autoFlush constructor parameter, which is false by default. Unlike the FileWriter, it will overwrite any existing file.
Files.write()
Java 7 introduced java.nio.file.Files. Files.write() lets you create and write to a file in a single call.
#icza's answer shows how to use this method. A couple of examples:
Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("foo", "bar");
try {
Files.write(Paths.get("file.txt"), "foo".getBytes(utf8));
Files.write(Paths.get("file2.txt"), lines, utf8);
} catch (IOException e) {}
This does not involve a buffer, so it's not suitable for large files.
Files.newBufferedWriter()
Java 7 also introduced Files.newBufferedWriter() which makes it easy to get a BufferedWriter:
Charset utf8 = StandardCharsets.UTF_8;
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("file.txt"), utf8)) {
writer.write("foo");
} catch (IOException e) {}
This is similar to PrintWriter, with the downside of not having PrintWriter's methods, and the benefit that it doesn't swallow exceptions.
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.
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
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.
Oh well, that rules out java.io.File. If a file cannot be written/appended, you may not be able to even know why.
We can continue looking at the tutorial: 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...-
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...-
Simplified example (Java 8 or 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.
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.
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.
Java is a great language, but the standard library is sometimes a bit low-level. Powerful, but low-level nonetheless.
Here are some of the possible ways to create and write a file in 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();
}
For further check this tutorial about How to read and write files in Java .
If you for some reason want to separate the act of creating and writing, the Java equivalent of touch is
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.
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);
}
best way is to use Java7:
Java 7 introduces a new way of working with the filesystem, along with a new utility class – Files. Using the Files class, we can create, move, copy, delete files and directories as well; it also can be used to read and write to a file.
public void saveDataInFile(String data) throws IOException {
Path path = Paths.get(fileName);
byte[] strToBytes = data.getBytes();
Files.write(path, strToBytes);
}
Write with FileChannel
If you are dealing with large files, FileChannel can be faster than standard IO. The following code write String to a file using FileChannel:
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();
}
Write with DataOutputStream
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
Let’s now see how we can use FileOutputStream to write binary data to a file. The following code converts a String int bytes and writes the bytes to file using a 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
we can use a PrintWriter to write formatted text to a file:
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:
use BufferedWriter to write a String to a new file:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(data);
writer.close();
}
append a String to the existing file:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(data);
writer.close();
}
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();
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
}
It's worth a try for Java 7+:
Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());
It looks promising...
In Java 8 use Files and Paths and using try-with-resources construct.
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
}
}
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();
}
}
}
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");
}
}
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+.
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());
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");
}
}
}
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);
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.
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.
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:
//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();
}
Using Google's Guava library, we can create and write to a file very
easily.
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.
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();
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");
There are at least several ways of creating a file and writing to it:
Small files (1.7)
You can use one of the write methods to write bytes, or lines, to a file.
Path file = Paths.get("path-to-file");
byte[] buf = "text-to-write-to-file".getBytes();
Files.write(file, buf);
These methods take care of most of the work for you, such as opening and closing the stream, but are not intended for handling large files.
Writing larger File by Using Buffered Stream I/O (1.7)
The java.nio.file package supports channel I/O, which moves data in buffers, bypassing some of the layers that can bottleneck stream I/O.
String s = "much-larger-text-to-write-to-file";
try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
writer.write(s, 0, s.length());
}
This approach is preferential due to its efficient performance especially when completing a large amount of write operations. Buffered operations have this effect as they aren’t required to call the operating system’s write method for every single byte, reducing on costly I/O operations.
Using NIO API to copy (and create a new one) a file with an Outputstream (1.7)
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);
}
There are also additional methods that allow to copy all bytes from an input stream to a file.
FileWriter (text) (<1.7)
Writes directly into file (less performance) and should be used only when number of writes are less. Used to write character-oriented data to a file.
String s= "some-text";
FileWriter fileWriter = new FileWriter("C:\\path\\to\\file\\file.txt");
fileWriter.write(fileContent);
fileWriter.close();
FileOutputStream (binary) (<1.7)
FileOutputStream is meant for writing streams of raw bytes such as image data.
byte data[] = "binary-to-write-to-file".getBytes();
FileOutputStream out = new FileOutputStream("file-name");
out.write(data);
out.close();
With this approach one should consider to always write an array of bytes rather than writing one byte at a time. The speedup can be quite significant - up to 10 x higher or more. Therefore it is recommended to use the write(byte[]) methods whenever possible.
Related
I need to append text repeatedly to an existing file in Java. How do I do that?
Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.
Java 7+
For a one-time task, the Files class makes this easy:
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Careful: The above approach will throw a NoSuchFileException if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE and APPEND options, which will create the file first if it doesn't already exist:
private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
s + System.lineSeparator(),
CREATE, APPEND
);
}
However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter is faster:
try(FileWriter fw = new FileWriter("myfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Notes:
The second parameter to the FileWriter constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)
Using a BufferedWriter is recommended for an expensive writer (such as FileWriter).
Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
But the BufferedWriter and PrintWriter wrappers are not strictly necessary.
Older Java
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Exception Handling
If you need robust exception handling for older Java, it gets very verbose:
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
You can use fileWriter with a flag set to true , for appending.
try
{
String filename= "MyFile.txt";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write("add a line\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
Shouldn't all of the answers here with try/catch blocks have the .close() pieces contained in a finally block?
Example for marked answer:
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
out.println("the text");
} catch (IOException e) {
System.err.println(e);
} finally {
if (out != null) {
out.close();
}
}
Also, as of Java 7, you can use a try-with-resources statement. No finally block is required for closing the declared resource(s) because it is handled automatically, and is also less verbose:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
out.println("the text");
} catch (IOException e) {
System.err.println(e);
}
Using Apache Commons 2.1:
import org.apache.logging.log4j.core.util.FileUtils;
FileUtils.writeStringToFile(file, "String to append", true);
Slightly expanding on Kip's answer,
here is a simple Java 7+ method to append a new line to a file, creating it if it doesn't already exist:
try {
final Path path = Paths.get("path/to/filename.txt");
Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
// Add your own exception handling...
}
Further notes:
The above uses the Files.write overload that writes lines of text to a file (i.e. similar to a println command). To just write text to the end (i.e. similar to a print command), an alternative Files.write overload can be used, passing in a byte array (e.g. "mytext".getBytes(StandardCharsets.UTF_8)).
The CREATE option will only work if the specified directory already exists - if it doesn't, a NoSuchFileException is thrown. If required, the following code could be added after setting path to create the directory structure:
Path pathParent = path.getParent();
if (!Files.exists(pathParent)) {
Files.createDirectories(pathParent);
}
Make sure the stream gets properly closed in all scenarios.
It's a bit alarming how many of these answers leave the file handle open in case of an error. The answer https://stackoverflow.com/a/15053443/2498188 is on the money but only because BufferedWriter() cannot throw. If it could then an exception would leave the FileWriter object open.
A more general way of doing this that doesn't care if BufferedWriter() can throw:
PrintWriter out = null;
BufferedWriter bw = null;
FileWriter fw = null;
try{
fw = new FileWriter("outfilename", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
finally{
try{
if( out != null ){
out.close(); // Will close bw and fw too
}
else if( bw != null ){
bw.close(); // Will close fw too
}
else if( fw != null ){
fw.close();
}
else{
// Oh boy did it fail hard! :3
}
}
catch( IOException e ){
// Closing the file writers failed for some obscure reason
}
}
Edit:
As of Java 7, the recommended way is to use "try with resources" and let the JVM deal with it:
try( FileWriter fw = new FileWriter("outfilename", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)){
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
In Java-7 it also can be done such kind:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
//---------------------
Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);
java 7+
In my humble opinion since I am fan of plain java, I would suggest something that it is a combination of the aforementioned answers. Maybe I am late for the party. Here is the code:
String sampleText = "test" + System.getProperty("line.separator");
Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
If the file doesn't exist, it creates it and if already exists it appends the
sampleText to the existing file. Using this, saves you from adding unnecessary libs to your classpath.
This can be done in one line of code. Hope this helps :)
Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);
I just add small detail:
new FileWriter("outfilename", true)
2.nd parameter (true) is a feature (or, interface) called appendable (http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html). It is responsible for being able to add some content to the end of particular file/stream. This interface is implemented since Java 1.5. Each object (i.e. BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer) with this interface can be used for adding content
In other words, you can add some content to your gzipped file, or some http process
Using java.nio.Files along with java.nio.file.StandardOpenOption
PrintWriter out = null;
BufferedWriter bufWriter;
try{
bufWriter =
Files.newBufferedWriter(
Paths.get("log.txt"),
Charset.forName("UTF8"),
StandardOpenOption.WRITE,
StandardOpenOption.APPEND,
StandardOpenOption.CREATE);
out = new PrintWriter(bufWriter, true);
}catch(IOException e){
//Oh, no! Failed to create PrintWriter
}
//After successful creation of PrintWriter
out.println("Text to be appended");
//After done writing, remember to close!
out.close();
This creates a BufferedWriter using Files, which accepts StandardOpenOption parameters, and an auto-flushing PrintWriter from the resultant BufferedWriter. PrintWriter's println() method, can then be called to write to the file.
The StandardOpenOption parameters used in this code: opens the file for writing, only appends to the file, and creates the file if it does not exist.
Paths.get("path here") can be replaced with new File("path here").toPath().
And Charset.forName("charset name") can be modified to accommodate the desired Charset.
Sample, using Guava:
File to = new File("C:/test/test.csv");
for (int i = 0; i < 42; i++) {
CharSequence from = "some string" + i + "\n";
Files.append(from, to, Charsets.UTF_8);
}
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);
the true allows to append the data in the existing file. If we will write
FileOutputStream fos = new FileOutputStream("File_Name");
It will overwrite the existing file. So go for first approach.
Try with bufferFileWriter.append, it works with me.
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
bufferFileWriter.append(obj.toJSONString());
bufferFileWriter.newLine();
bufferFileWriter.close();
} catch (IOException ex) {
Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Writer {
public static void main(String args[]){
doWrite("output.txt","Content to be appended to file");
}
public static void doWrite(String filePath,String contentToBeAppended){
try(
FileWriter fw = new FileWriter(filePath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)
)
{
out.println(contentToBeAppended);
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
}
}
String str;
String path = "C:/Users/...the path..../iin.txt"; // you can input also..i created this way :P
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new FileWriter(path, true));
try
{
while(true)
{
System.out.println("Enter the text : ");
str = br.readLine();
if(str.equalsIgnoreCase("exit"))
break;
else
pw.println(str);
}
}
catch (Exception e)
{
//oh noes!
}
finally
{
pw.close();
}
this will do what you intend for..
You can also try this :
JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file
try
{
RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
long length = raf.length();
//System.out.println(length);
raf.setLength(length + 1); //+ (integer value) for spacing
raf.seek(raf.length());
raf.writeBytes(Content);
raf.close();
}
catch (Exception e) {
//any exception handling method of ur choice
}
Better to use try-with-resources then all that pre-java 7 finally business
static void appendStringToFile(Path file, String s) throws IOException {
try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
out.append(s);
out.newLine();
}
}
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.
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.
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:
//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();
}
FileOutputStream stream = new FileOutputStream(path, true);
try {
stream.write(
string.getBytes("UTF-8") // Choose your encoding.
);
} finally {
stream.close();
}
Then catch an IOException somewhere upstream.
Create a function anywhere in your project and simply call that function where ever you need it.
Guys you got to remember that you guys are calling active threads that you are not calling asynchronously and since it would likely be a good 5 to 10 pages to get it done right.
Why not spend more time on your project and forget about writing anything already written.
Properly
//Adding a static modifier would make this accessible anywhere in your app
public Logger getLogger()
{
return java.util.logging.Logger.getLogger("MyLogFileName");
}
//call the method anywhere and append what you want to log
//Logger class will take care of putting timestamps for you
//plus the are ansychronously done so more of the
//processing power will go into your application
//from inside a function body in the same class ...{...
getLogger().log(Level.INFO,"the text you want to append");
...}...
/*********log file resides in server root log files********/
three lines of code two really since the third actually appends text. :P
Library
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
Code
public void append()
{
try
{
String path = "D:/sample.txt";
File file = new File(path);
FileWriter fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
fileWriter.append("Sample text in the file to append");
bufferFileWriter.close();
System.out.println("User Registration Completed");
}catch(Exception ex)
{
System.out.println(ex);
}
}
I might suggest the apache commons project. This project already provides a framework for doing what you need (i.e. flexible filtering of collections).
The following method let's you append text to some file:
private void appendToFile(String filePath, String text)
{
PrintWriter fileWriter = null;
try
{
fileWriter = new PrintWriter(new BufferedWriter(new FileWriter(
filePath, true)));
fileWriter.println(text);
} catch (IOException ioException)
{
ioException.printStackTrace();
} finally
{
if (fileWriter != null)
{
fileWriter.close();
}
}
}
Alternatively using FileUtils:
public static void appendToFile(String filePath, String text) throws IOException
{
File file = new File(filePath);
if(!file.exists())
{
file.createNewFile();
}
String fileContents = FileUtils.readFileToString(file);
if(file.length() != 0)
{
fileContents = fileContents.concat(System.lineSeparator());
}
fileContents = fileContents.concat(text);
FileUtils.writeStringToFile(file, fileContents);
}
It is not efficient but works fine. Line breaks are handled correctly and a new file is created if one didn't exist yet.
This code will fulifil your need:
FileWriter fw=new FileWriter("C:\\file.json",true);
fw.write("ssssss");
fw.close();
In case you want to ADD SOME TEXT IN SPECIFIC LINES you can first read the whole file, append the text wherever you want and then overwrite everything like in the code below:
public static void addDatatoFile(String data1, String data2){
String fullPath = "/home/user/dir/file.csv";
File dir = new File(fullPath);
List<String> l = new LinkedList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
String line;
int count = 0;
while ((line = br.readLine()) != null) {
if(count == 1){
//add data at the end of second line
line += data1;
}else if(count == 2){
//add other data at the end of third line
line += data2;
}
l.add(line);
count++;
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
createFileFromList(l, dir);
}
public static void createFileFromList(List<String> list, File f){
PrintWriter writer;
try {
writer = new PrintWriter(f, "UTF-8");
for (String d : list) {
writer.println(d.toString());
}
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
My answer:
JFileChooser chooser= new JFileChooser();
chooser.showOpenDialog(chooser);
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";
try
{
RandomAccessFile random = new RandomAccessFile(file, "rw");
long length = random.length();
random.setLength(length + 1);
random.seek(random.length());
random.writeBytes(Content);
random.close();
}
catch (Exception exception) {
//exception handling
}
/**********************************************************************
* it will write content to a specified file
*
* #param keyString
* #throws IOException
*********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
// For output to file
File a = new File(textFilePAth);
if (!a.exists()) {
a.createNewFile();
}
FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(keyString);
bw.newLine();
bw.close();
}// end of writeToFile()
For JDK version >= 7
You can utilise this simple method which appends the given content to the specified file:
void appendToFile(String filePath, String content) {
try (FileWriter fw = new FileWriter(filePath, true)) {
fw.write(content + System.lineSeparator());
} catch (IOException e) {
// TODO handle exception
}
}
We are constructing a FileWriter object in append mode.
You can use the follong code to append the content in the file:
String fileName="/home/shriram/Desktop/Images/"+"test.txt";
FileWriter fw=new FileWriter(fileName,true);
fw.write("here will be you content to insert or append in file");
fw.close();
FileWriter fw1=new FileWriter(fileName,true);
fw1.write("another content will be here to be append in the same file");
fw1.close();
I need to append text repeatedly to an existing file in Java. How do I do that?
Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.
Java 7+
For a one-time task, the Files class makes this easy:
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Careful: The above approach will throw a NoSuchFileException if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE and APPEND options, which will create the file first if it doesn't already exist:
private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
s + System.lineSeparator(),
CREATE, APPEND
);
}
However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter is faster:
try(FileWriter fw = new FileWriter("myfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Notes:
The second parameter to the FileWriter constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)
Using a BufferedWriter is recommended for an expensive writer (such as FileWriter).
Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
But the BufferedWriter and PrintWriter wrappers are not strictly necessary.
Older Java
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Exception Handling
If you need robust exception handling for older Java, it gets very verbose:
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
You can use fileWriter with a flag set to true , for appending.
try
{
String filename= "MyFile.txt";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write("add a line\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
Shouldn't all of the answers here with try/catch blocks have the .close() pieces contained in a finally block?
Example for marked answer:
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
out.println("the text");
} catch (IOException e) {
System.err.println(e);
} finally {
if (out != null) {
out.close();
}
}
Also, as of Java 7, you can use a try-with-resources statement. No finally block is required for closing the declared resource(s) because it is handled automatically, and is also less verbose:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
out.println("the text");
} catch (IOException e) {
System.err.println(e);
}
Using Apache Commons 2.1:
import org.apache.logging.log4j.core.util.FileUtils;
FileUtils.writeStringToFile(file, "String to append", true);
Slightly expanding on Kip's answer,
here is a simple Java 7+ method to append a new line to a file, creating it if it doesn't already exist:
try {
final Path path = Paths.get("path/to/filename.txt");
Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
// Add your own exception handling...
}
Further notes:
The above uses the Files.write overload that writes lines of text to a file (i.e. similar to a println command). To just write text to the end (i.e. similar to a print command), an alternative Files.write overload can be used, passing in a byte array (e.g. "mytext".getBytes(StandardCharsets.UTF_8)).
The CREATE option will only work if the specified directory already exists - if it doesn't, a NoSuchFileException is thrown. If required, the following code could be added after setting path to create the directory structure:
Path pathParent = path.getParent();
if (!Files.exists(pathParent)) {
Files.createDirectories(pathParent);
}
Make sure the stream gets properly closed in all scenarios.
It's a bit alarming how many of these answers leave the file handle open in case of an error. The answer https://stackoverflow.com/a/15053443/2498188 is on the money but only because BufferedWriter() cannot throw. If it could then an exception would leave the FileWriter object open.
A more general way of doing this that doesn't care if BufferedWriter() can throw:
PrintWriter out = null;
BufferedWriter bw = null;
FileWriter fw = null;
try{
fw = new FileWriter("outfilename", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
finally{
try{
if( out != null ){
out.close(); // Will close bw and fw too
}
else if( bw != null ){
bw.close(); // Will close fw too
}
else if( fw != null ){
fw.close();
}
else{
// Oh boy did it fail hard! :3
}
}
catch( IOException e ){
// Closing the file writers failed for some obscure reason
}
}
Edit:
As of Java 7, the recommended way is to use "try with resources" and let the JVM deal with it:
try( FileWriter fw = new FileWriter("outfilename", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)){
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
In Java-7 it also can be done such kind:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
//---------------------
Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);
java 7+
In my humble opinion since I am fan of plain java, I would suggest something that it is a combination of the aforementioned answers. Maybe I am late for the party. Here is the code:
String sampleText = "test" + System.getProperty("line.separator");
Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
If the file doesn't exist, it creates it and if already exists it appends the
sampleText to the existing file. Using this, saves you from adding unnecessary libs to your classpath.
This can be done in one line of code. Hope this helps :)
Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);
I just add small detail:
new FileWriter("outfilename", true)
2.nd parameter (true) is a feature (or, interface) called appendable (http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html). It is responsible for being able to add some content to the end of particular file/stream. This interface is implemented since Java 1.5. Each object (i.e. BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer) with this interface can be used for adding content
In other words, you can add some content to your gzipped file, or some http process
Using java.nio.Files along with java.nio.file.StandardOpenOption
PrintWriter out = null;
BufferedWriter bufWriter;
try{
bufWriter =
Files.newBufferedWriter(
Paths.get("log.txt"),
Charset.forName("UTF8"),
StandardOpenOption.WRITE,
StandardOpenOption.APPEND,
StandardOpenOption.CREATE);
out = new PrintWriter(bufWriter, true);
}catch(IOException e){
//Oh, no! Failed to create PrintWriter
}
//After successful creation of PrintWriter
out.println("Text to be appended");
//After done writing, remember to close!
out.close();
This creates a BufferedWriter using Files, which accepts StandardOpenOption parameters, and an auto-flushing PrintWriter from the resultant BufferedWriter. PrintWriter's println() method, can then be called to write to the file.
The StandardOpenOption parameters used in this code: opens the file for writing, only appends to the file, and creates the file if it does not exist.
Paths.get("path here") can be replaced with new File("path here").toPath().
And Charset.forName("charset name") can be modified to accommodate the desired Charset.
Sample, using Guava:
File to = new File("C:/test/test.csv");
for (int i = 0; i < 42; i++) {
CharSequence from = "some string" + i + "\n";
Files.append(from, to, Charsets.UTF_8);
}
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);
the true allows to append the data in the existing file. If we will write
FileOutputStream fos = new FileOutputStream("File_Name");
It will overwrite the existing file. So go for first approach.
Try with bufferFileWriter.append, it works with me.
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
bufferFileWriter.append(obj.toJSONString());
bufferFileWriter.newLine();
bufferFileWriter.close();
} catch (IOException ex) {
Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Writer {
public static void main(String args[]){
doWrite("output.txt","Content to be appended to file");
}
public static void doWrite(String filePath,String contentToBeAppended){
try(
FileWriter fw = new FileWriter(filePath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)
)
{
out.println(contentToBeAppended);
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
}
}
String str;
String path = "C:/Users/...the path..../iin.txt"; // you can input also..i created this way :P
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new FileWriter(path, true));
try
{
while(true)
{
System.out.println("Enter the text : ");
str = br.readLine();
if(str.equalsIgnoreCase("exit"))
break;
else
pw.println(str);
}
}
catch (Exception e)
{
//oh noes!
}
finally
{
pw.close();
}
this will do what you intend for..
You can also try this :
JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file
try
{
RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
long length = raf.length();
//System.out.println(length);
raf.setLength(length + 1); //+ (integer value) for spacing
raf.seek(raf.length());
raf.writeBytes(Content);
raf.close();
}
catch (Exception e) {
//any exception handling method of ur choice
}
Better to use try-with-resources then all that pre-java 7 finally business
static void appendStringToFile(Path file, String s) throws IOException {
try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
out.append(s);
out.newLine();
}
}
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.
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.
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:
//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();
}
FileOutputStream stream = new FileOutputStream(path, true);
try {
stream.write(
string.getBytes("UTF-8") // Choose your encoding.
);
} finally {
stream.close();
}
Then catch an IOException somewhere upstream.
Create a function anywhere in your project and simply call that function where ever you need it.
Guys you got to remember that you guys are calling active threads that you are not calling asynchronously and since it would likely be a good 5 to 10 pages to get it done right.
Why not spend more time on your project and forget about writing anything already written.
Properly
//Adding a static modifier would make this accessible anywhere in your app
public Logger getLogger()
{
return java.util.logging.Logger.getLogger("MyLogFileName");
}
//call the method anywhere and append what you want to log
//Logger class will take care of putting timestamps for you
//plus the are ansychronously done so more of the
//processing power will go into your application
//from inside a function body in the same class ...{...
getLogger().log(Level.INFO,"the text you want to append");
...}...
/*********log file resides in server root log files********/
three lines of code two really since the third actually appends text. :P
Library
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
Code
public void append()
{
try
{
String path = "D:/sample.txt";
File file = new File(path);
FileWriter fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
fileWriter.append("Sample text in the file to append");
bufferFileWriter.close();
System.out.println("User Registration Completed");
}catch(Exception ex)
{
System.out.println(ex);
}
}
I might suggest the apache commons project. This project already provides a framework for doing what you need (i.e. flexible filtering of collections).
The following method let's you append text to some file:
private void appendToFile(String filePath, String text)
{
PrintWriter fileWriter = null;
try
{
fileWriter = new PrintWriter(new BufferedWriter(new FileWriter(
filePath, true)));
fileWriter.println(text);
} catch (IOException ioException)
{
ioException.printStackTrace();
} finally
{
if (fileWriter != null)
{
fileWriter.close();
}
}
}
Alternatively using FileUtils:
public static void appendToFile(String filePath, String text) throws IOException
{
File file = new File(filePath);
if(!file.exists())
{
file.createNewFile();
}
String fileContents = FileUtils.readFileToString(file);
if(file.length() != 0)
{
fileContents = fileContents.concat(System.lineSeparator());
}
fileContents = fileContents.concat(text);
FileUtils.writeStringToFile(file, fileContents);
}
It is not efficient but works fine. Line breaks are handled correctly and a new file is created if one didn't exist yet.
This code will fulifil your need:
FileWriter fw=new FileWriter("C:\\file.json",true);
fw.write("ssssss");
fw.close();
In case you want to ADD SOME TEXT IN SPECIFIC LINES you can first read the whole file, append the text wherever you want and then overwrite everything like in the code below:
public static void addDatatoFile(String data1, String data2){
String fullPath = "/home/user/dir/file.csv";
File dir = new File(fullPath);
List<String> l = new LinkedList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
String line;
int count = 0;
while ((line = br.readLine()) != null) {
if(count == 1){
//add data at the end of second line
line += data1;
}else if(count == 2){
//add other data at the end of third line
line += data2;
}
l.add(line);
count++;
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
createFileFromList(l, dir);
}
public static void createFileFromList(List<String> list, File f){
PrintWriter writer;
try {
writer = new PrintWriter(f, "UTF-8");
for (String d : list) {
writer.println(d.toString());
}
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
My answer:
JFileChooser chooser= new JFileChooser();
chooser.showOpenDialog(chooser);
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";
try
{
RandomAccessFile random = new RandomAccessFile(file, "rw");
long length = random.length();
random.setLength(length + 1);
random.seek(random.length());
random.writeBytes(Content);
random.close();
}
catch (Exception exception) {
//exception handling
}
/**********************************************************************
* it will write content to a specified file
*
* #param keyString
* #throws IOException
*********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
// For output to file
File a = new File(textFilePAth);
if (!a.exists()) {
a.createNewFile();
}
FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(keyString);
bw.newLine();
bw.close();
}// end of writeToFile()
For JDK version >= 7
You can utilise this simple method which appends the given content to the specified file:
void appendToFile(String filePath, String content) {
try (FileWriter fw = new FileWriter(filePath, true)) {
fw.write(content + System.lineSeparator());
} catch (IOException e) {
// TODO handle exception
}
}
We are constructing a FileWriter object in append mode.
You can use the follong code to append the content in the file:
String fileName="/home/shriram/Desktop/Images/"+"test.txt";
FileWriter fw=new FileWriter(fileName,true);
fw.write("here will be you content to insert or append in file");
fw.close();
FileWriter fw1=new FileWriter(fileName,true);
fw1.write("another content will be here to be append in the same file");
fw1.close();
I need to append text repeatedly to an existing file in Java. How do I do that?
Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.
Java 7+
For a one-time task, the Files class makes this easy:
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Careful: The above approach will throw a NoSuchFileException if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE and APPEND options, which will create the file first if it doesn't already exist:
private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
s + System.lineSeparator(),
CREATE, APPEND
);
}
However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter is faster:
try(FileWriter fw = new FileWriter("myfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Notes:
The second parameter to the FileWriter constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)
Using a BufferedWriter is recommended for an expensive writer (such as FileWriter).
Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
But the BufferedWriter and PrintWriter wrappers are not strictly necessary.
Older Java
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Exception Handling
If you need robust exception handling for older Java, it gets very verbose:
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
You can use fileWriter with a flag set to true , for appending.
try
{
String filename= "MyFile.txt";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write("add a line\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
Shouldn't all of the answers here with try/catch blocks have the .close() pieces contained in a finally block?
Example for marked answer:
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
out.println("the text");
} catch (IOException e) {
System.err.println(e);
} finally {
if (out != null) {
out.close();
}
}
Also, as of Java 7, you can use a try-with-resources statement. No finally block is required for closing the declared resource(s) because it is handled automatically, and is also less verbose:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
out.println("the text");
} catch (IOException e) {
System.err.println(e);
}
Using Apache Commons 2.1:
import org.apache.logging.log4j.core.util.FileUtils;
FileUtils.writeStringToFile(file, "String to append", true);
Slightly expanding on Kip's answer,
here is a simple Java 7+ method to append a new line to a file, creating it if it doesn't already exist:
try {
final Path path = Paths.get("path/to/filename.txt");
Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
// Add your own exception handling...
}
Further notes:
The above uses the Files.write overload that writes lines of text to a file (i.e. similar to a println command). To just write text to the end (i.e. similar to a print command), an alternative Files.write overload can be used, passing in a byte array (e.g. "mytext".getBytes(StandardCharsets.UTF_8)).
The CREATE option will only work if the specified directory already exists - if it doesn't, a NoSuchFileException is thrown. If required, the following code could be added after setting path to create the directory structure:
Path pathParent = path.getParent();
if (!Files.exists(pathParent)) {
Files.createDirectories(pathParent);
}
Make sure the stream gets properly closed in all scenarios.
It's a bit alarming how many of these answers leave the file handle open in case of an error. The answer https://stackoverflow.com/a/15053443/2498188 is on the money but only because BufferedWriter() cannot throw. If it could then an exception would leave the FileWriter object open.
A more general way of doing this that doesn't care if BufferedWriter() can throw:
PrintWriter out = null;
BufferedWriter bw = null;
FileWriter fw = null;
try{
fw = new FileWriter("outfilename", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
finally{
try{
if( out != null ){
out.close(); // Will close bw and fw too
}
else if( bw != null ){
bw.close(); // Will close fw too
}
else if( fw != null ){
fw.close();
}
else{
// Oh boy did it fail hard! :3
}
}
catch( IOException e ){
// Closing the file writers failed for some obscure reason
}
}
Edit:
As of Java 7, the recommended way is to use "try with resources" and let the JVM deal with it:
try( FileWriter fw = new FileWriter("outfilename", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)){
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
In Java-7 it also can be done such kind:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
//---------------------
Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);
java 7+
In my humble opinion since I am fan of plain java, I would suggest something that it is a combination of the aforementioned answers. Maybe I am late for the party. Here is the code:
String sampleText = "test" + System.getProperty("line.separator");
Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
If the file doesn't exist, it creates it and if already exists it appends the
sampleText to the existing file. Using this, saves you from adding unnecessary libs to your classpath.
This can be done in one line of code. Hope this helps :)
Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);
I just add small detail:
new FileWriter("outfilename", true)
2.nd parameter (true) is a feature (or, interface) called appendable (http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html). It is responsible for being able to add some content to the end of particular file/stream. This interface is implemented since Java 1.5. Each object (i.e. BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer) with this interface can be used for adding content
In other words, you can add some content to your gzipped file, or some http process
Using java.nio.Files along with java.nio.file.StandardOpenOption
PrintWriter out = null;
BufferedWriter bufWriter;
try{
bufWriter =
Files.newBufferedWriter(
Paths.get("log.txt"),
Charset.forName("UTF8"),
StandardOpenOption.WRITE,
StandardOpenOption.APPEND,
StandardOpenOption.CREATE);
out = new PrintWriter(bufWriter, true);
}catch(IOException e){
//Oh, no! Failed to create PrintWriter
}
//After successful creation of PrintWriter
out.println("Text to be appended");
//After done writing, remember to close!
out.close();
This creates a BufferedWriter using Files, which accepts StandardOpenOption parameters, and an auto-flushing PrintWriter from the resultant BufferedWriter. PrintWriter's println() method, can then be called to write to the file.
The StandardOpenOption parameters used in this code: opens the file for writing, only appends to the file, and creates the file if it does not exist.
Paths.get("path here") can be replaced with new File("path here").toPath().
And Charset.forName("charset name") can be modified to accommodate the desired Charset.
Sample, using Guava:
File to = new File("C:/test/test.csv");
for (int i = 0; i < 42; i++) {
CharSequence from = "some string" + i + "\n";
Files.append(from, to, Charsets.UTF_8);
}
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);
the true allows to append the data in the existing file. If we will write
FileOutputStream fos = new FileOutputStream("File_Name");
It will overwrite the existing file. So go for first approach.
Try with bufferFileWriter.append, it works with me.
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
bufferFileWriter.append(obj.toJSONString());
bufferFileWriter.newLine();
bufferFileWriter.close();
} catch (IOException ex) {
Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Writer {
public static void main(String args[]){
doWrite("output.txt","Content to be appended to file");
}
public static void doWrite(String filePath,String contentToBeAppended){
try(
FileWriter fw = new FileWriter(filePath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)
)
{
out.println(contentToBeAppended);
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
}
}
String str;
String path = "C:/Users/...the path..../iin.txt"; // you can input also..i created this way :P
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new FileWriter(path, true));
try
{
while(true)
{
System.out.println("Enter the text : ");
str = br.readLine();
if(str.equalsIgnoreCase("exit"))
break;
else
pw.println(str);
}
}
catch (Exception e)
{
//oh noes!
}
finally
{
pw.close();
}
this will do what you intend for..
You can also try this :
JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file
try
{
RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
long length = raf.length();
//System.out.println(length);
raf.setLength(length + 1); //+ (integer value) for spacing
raf.seek(raf.length());
raf.writeBytes(Content);
raf.close();
}
catch (Exception e) {
//any exception handling method of ur choice
}
Better to use try-with-resources then all that pre-java 7 finally business
static void appendStringToFile(Path file, String s) throws IOException {
try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
out.append(s);
out.newLine();
}
}
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.
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.
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:
//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();
}
FileOutputStream stream = new FileOutputStream(path, true);
try {
stream.write(
string.getBytes("UTF-8") // Choose your encoding.
);
} finally {
stream.close();
}
Then catch an IOException somewhere upstream.
Create a function anywhere in your project and simply call that function where ever you need it.
Guys you got to remember that you guys are calling active threads that you are not calling asynchronously and since it would likely be a good 5 to 10 pages to get it done right.
Why not spend more time on your project and forget about writing anything already written.
Properly
//Adding a static modifier would make this accessible anywhere in your app
public Logger getLogger()
{
return java.util.logging.Logger.getLogger("MyLogFileName");
}
//call the method anywhere and append what you want to log
//Logger class will take care of putting timestamps for you
//plus the are ansychronously done so more of the
//processing power will go into your application
//from inside a function body in the same class ...{...
getLogger().log(Level.INFO,"the text you want to append");
...}...
/*********log file resides in server root log files********/
three lines of code two really since the third actually appends text. :P
Library
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
Code
public void append()
{
try
{
String path = "D:/sample.txt";
File file = new File(path);
FileWriter fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
fileWriter.append("Sample text in the file to append");
bufferFileWriter.close();
System.out.println("User Registration Completed");
}catch(Exception ex)
{
System.out.println(ex);
}
}
I might suggest the apache commons project. This project already provides a framework for doing what you need (i.e. flexible filtering of collections).
The following method let's you append text to some file:
private void appendToFile(String filePath, String text)
{
PrintWriter fileWriter = null;
try
{
fileWriter = new PrintWriter(new BufferedWriter(new FileWriter(
filePath, true)));
fileWriter.println(text);
} catch (IOException ioException)
{
ioException.printStackTrace();
} finally
{
if (fileWriter != null)
{
fileWriter.close();
}
}
}
Alternatively using FileUtils:
public static void appendToFile(String filePath, String text) throws IOException
{
File file = new File(filePath);
if(!file.exists())
{
file.createNewFile();
}
String fileContents = FileUtils.readFileToString(file);
if(file.length() != 0)
{
fileContents = fileContents.concat(System.lineSeparator());
}
fileContents = fileContents.concat(text);
FileUtils.writeStringToFile(file, fileContents);
}
It is not efficient but works fine. Line breaks are handled correctly and a new file is created if one didn't exist yet.
This code will fulifil your need:
FileWriter fw=new FileWriter("C:\\file.json",true);
fw.write("ssssss");
fw.close();
In case you want to ADD SOME TEXT IN SPECIFIC LINES you can first read the whole file, append the text wherever you want and then overwrite everything like in the code below:
public static void addDatatoFile(String data1, String data2){
String fullPath = "/home/user/dir/file.csv";
File dir = new File(fullPath);
List<String> l = new LinkedList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
String line;
int count = 0;
while ((line = br.readLine()) != null) {
if(count == 1){
//add data at the end of second line
line += data1;
}else if(count == 2){
//add other data at the end of third line
line += data2;
}
l.add(line);
count++;
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
createFileFromList(l, dir);
}
public static void createFileFromList(List<String> list, File f){
PrintWriter writer;
try {
writer = new PrintWriter(f, "UTF-8");
for (String d : list) {
writer.println(d.toString());
}
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
My answer:
JFileChooser chooser= new JFileChooser();
chooser.showOpenDialog(chooser);
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";
try
{
RandomAccessFile random = new RandomAccessFile(file, "rw");
long length = random.length();
random.setLength(length + 1);
random.seek(random.length());
random.writeBytes(Content);
random.close();
}
catch (Exception exception) {
//exception handling
}
/**********************************************************************
* it will write content to a specified file
*
* #param keyString
* #throws IOException
*********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
// For output to file
File a = new File(textFilePAth);
if (!a.exists()) {
a.createNewFile();
}
FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(keyString);
bw.newLine();
bw.close();
}// end of writeToFile()
For JDK version >= 7
You can utilise this simple method which appends the given content to the specified file:
void appendToFile(String filePath, String content) {
try (FileWriter fw = new FileWriter(filePath, true)) {
fw.write(content + System.lineSeparator());
} catch (IOException e) {
// TODO handle exception
}
}
We are constructing a FileWriter object in append mode.
You can use the follong code to append the content in the file:
String fileName="/home/shriram/Desktop/Images/"+"test.txt";
FileWriter fw=new FileWriter(fileName,true);
fw.write("here will be you content to insert or append in file");
fw.close();
FileWriter fw1=new FileWriter(fileName,true);
fw1.write("another content will be here to be append in the same file");
fw1.close();
I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D
I searched the web and found this code, but I understand 50% of it.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
With Java 7 and up, a one liner using Files:
String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
You could do this by using JAVA 7 new File API.
code sample:
`
public class FileWriter7 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
writeSmallTextFile(lines, filepath);
}
private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aLines, StandardCharsets.UTF_8);
}
}
`
You can use FileUtils from Apache Commons:
import org.apache.commons.io.FileUtils;
final File file = new File("test.txt");
FileUtils.writeStringToFile(file, "your content", StandardCharsets.UTF_8);
Appending the file FileWriter(String fileName,
boolean append)
try { // this is for monitoring runtime Exception within the block
String content = "This is the content to write into file"; // content to write into the file
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here
// if file doesnt exists, then create it
if (!file.exists()) { // checks whether the file is Exist or not
file.createNewFile(); // here if file not exist new file created
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
bw.write(content); // write method is used to write the given content into the file
bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.
System.out.println("Done");
} catch (IOException e) { // if any exception occurs it will catch
e.printStackTrace();
}
Your code is the simplest. But, i always try to optimize the code further. Here is a sample.
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
bw.write("Hello, This is a test message");
bw.close();
}catch (FileNotFoundException ex) {
System.out.println(ex.toString());
}
Files.write() the simple solution as #Dilip Kumar said. I used to use that way untill I faced an issue, can not affect line separator (Unix/Windows) CR LF.
So now I use a Java 8 stream file writing way, what allows me to manipulate the content on the fly. :)
List<String> lines = Arrays.asList(new String[] { "line1", "line2" });
Path path = Paths.get(fullFileName);
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write(lines.stream()
.reduce((sum,currLine) -> sum + "\n" + currLine)
.get());
}
In this way, I can specify the line separator or I can do any kind of magic like TRIM, Uppercase, filtering etc.
String content = "your content here";
Path path = Paths.get("/data/output.txt");
if(!Files.exists(path)){
Files.createFile(path);
}
BufferedWriter writer = Files.newBufferedWriter(path);
writer.write(content);
In Java 11 or Later, writeString can be used from java.nio.file.Files,
String content = "This is my content";
String fileName = "myFile.txt";
Files.writeString(Paths.get(fileName), content);
With Options:
Files.writeString(Paths.get(fileName), content, StandardOpenOption.CREATE)
More documentation about the java.nio.file.Files and StandardOpenOption
File file = new File("path/file.name");
IOUtils.write("content", new FileOutputStream(file));
IOUtils also can be used to write/read files easily with java 8.
What's the simplest way to create and write to a (text) file in Java?
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.
Note that each of the code samples below will overwrite the file if it already exists
Creating a text file:
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:
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:
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, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.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);
In Java 7 and 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
Files.write(..) from guava
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.
Below is the original, prior-to-Java 7 answer
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).
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.
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:
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();
}
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 ) {
try {
output.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
}
A very simple way to create and write to a file in 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);
}
}
}
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();
}
}
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.
This feature was introduced in Java 7.
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.
There are many ways of writing to a file. Each has its benefits, and each might be simplest in a given scenario.
This answer is centred on Java 8, and tries to cover all the details needed for the Java Professional Exam. Classes involved include:
.
├── OutputStream
│ └── FileOutputStream
├── Writer
│ ├── OutputStreamWriter
│ │ └── FileWriter
│ ├── BufferedWriter
│ └── PrintWriter (Java 5+)
└── Files (Java 7+)
There are 5 main ways of writing to a file:
┌───────────────────────────┬────────────────────────┬─────────────┬──────────────┐
│ │ Buffer for │ Can specify │ Throws │
│ │ large files? │ encoding? │ IOException? │
├───────────────────────────┼────────────────────────┼─────────────┼──────────────┤
│ OutputStreamWriter │ Wrap in BufferedWriter │ Y │ Y │
│ FileWriter │ Wrap in BufferedWriter │ │ Y │
│ PrintWriter │ Y │ Y │ │
│ Files.write() │ │ Y │ Y │
│ Files.newBufferedWriter() │ Y │ Y │ Y │
└───────────────────────────┴────────────────────────┴─────────────┴──────────────┘
Each has its own distinctive benefits:
OutputStreamWriter - The most basic way before Java 5
FileWriter – Optional append constructor argument
PrintWriter – Lots of methods
Files.write() – Create and write to a file in a single call
Files.newBufferedWriter() – Makes it easy to write large files
Below are details of each.
FileOutputStream
This class is meant for writing streams of raw bytes. All the Writer approaches below rely on this class, either explicitly or under the hood.
try (FileOutputStream stream = new FileOutputStream("file.txt");) {
byte data[] = "foo".getBytes();
stream.write(data);
} catch (IOException e) {}
Note that the try-with-resources statement takes care of stream.close() and that closing the stream flushes it, like stream.flush().
OutputStreamWriter
This class is a bridge from character streams to byte streams. It can wrap a FileOutputStream, and write strings:
Charset utf8 = StandardCharsets.UTF_8;
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File("file.txt")), utf8)) {
writer.write("foo");
} catch (IOException e) {}
BufferedWriter
This class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
It can wrap an OutputStreamWriter:
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("file.txt"))))) {
writer.write("foo");
writer.newLine(); // method provided by BufferedWriter
} catch (IOException e) {}
Pre Java 5 this was the best approach for large files (with a regular try/catch block).
FileWriter
This is a subclass of the OutputStreamWriter, and is a convenience class for writing character files:
boolean append = false;
try(FileWriter writer = new FileWriter("file.txt", append) ){
writer.write("foo");
writer.append("bar");
} catch (IOException e) {}
The key benefit is that it has an optional append constructor argument, which determines whether it appends to or overwrites the existing file. Note that the append/overwrite behaviour is not controlled by the write() and append() methods, which behave in nearly the same way.
Note that:
There is no buffering, but to handle large files it can be wrapped in a BufferedWriter.
FileWriter uses the default encoding. It's often preferable to specify encoding explicitly
PrintWriter
This class prints formatted representations of objects to a text-output stream. Under the hood it is the same as the BufferedWriter approach above (new BufferedWriter(new OutputStreamWriter(new FileOutputStream(...)))). PrintWriter was introduced in Java 5 as a convenient way to call this idiom, and adds additional methods such as printf() and println().
Methods in this class don't throw I/O exceptions. You can check errors by calling checkError(). The destination of a PrintWriter instance can be a File, OutputStream or Writer. Here is an example of writing to a file:
try (PrintWriter writer = new PrintWriter("file.txt", "UTF-8")) {
writer.print("foo");
writer.printf("bar %d $", "a", 1);
writer.println("baz");
} catch (FileNotFoundException e) {
} catch (UnsupportedEncodingException e) {}
When writing to an OutputStream or Writer there is an optional autoFlush constructor parameter, which is false by default. Unlike the FileWriter, it will overwrite any existing file.
Files.write()
Java 7 introduced java.nio.file.Files. Files.write() lets you create and write to a file in a single call.
#icza's answer shows how to use this method. A couple of examples:
Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("foo", "bar");
try {
Files.write(Paths.get("file.txt"), "foo".getBytes(utf8));
Files.write(Paths.get("file2.txt"), lines, utf8);
} catch (IOException e) {}
This does not involve a buffer, so it's not suitable for large files.
Files.newBufferedWriter()
Java 7 also introduced Files.newBufferedWriter() which makes it easy to get a BufferedWriter:
Charset utf8 = StandardCharsets.UTF_8;
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("file.txt"), utf8)) {
writer.write("foo");
} catch (IOException e) {}
This is similar to PrintWriter, with the downside of not having PrintWriter's methods, and the benefit that it doesn't swallow exceptions.
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.
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
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.
Oh well, that rules out java.io.File. If a file cannot be written/appended, you may not be able to even know why.
We can continue looking at the tutorial: 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...-
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...-
Simplified example (Java 8 or 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.
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.
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.
Java is a great language, but the standard library is sometimes a bit low-level. Powerful, but low-level nonetheless.
Here are some of the possible ways to create and write a file in 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();
}
For further check this tutorial about How to read and write files in Java .
If you for some reason want to separate the act of creating and writing, the Java equivalent of touch is
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.
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);
}
best way is to use Java7:
Java 7 introduces a new way of working with the filesystem, along with a new utility class – Files. Using the Files class, we can create, move, copy, delete files and directories as well; it also can be used to read and write to a file.
public void saveDataInFile(String data) throws IOException {
Path path = Paths.get(fileName);
byte[] strToBytes = data.getBytes();
Files.write(path, strToBytes);
}
Write with FileChannel
If you are dealing with large files, FileChannel can be faster than standard IO. The following code write String to a file using FileChannel:
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();
}
Write with DataOutputStream
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
Let’s now see how we can use FileOutputStream to write binary data to a file. The following code converts a String int bytes and writes the bytes to file using a 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
we can use a PrintWriter to write formatted text to a file:
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:
use BufferedWriter to write a String to a new file:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(data);
writer.close();
}
append a String to the existing file:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(data);
writer.close();
}
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();
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
}
It's worth a try for Java 7+:
Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());
It looks promising...
In Java 8 use Files and Paths and using try-with-resources construct.
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
}
}
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();
}
}
}
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");
}
}
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+.
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());
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");
}
}
}
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);
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.
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.
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:
//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();
}
Using Google's Guava library, we can create and write to a file very
easily.
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.
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();
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");
There are at least several ways of creating a file and writing to it:
Small files (1.7)
You can use one of the write methods to write bytes, or lines, to a file.
Path file = Paths.get("path-to-file");
byte[] buf = "text-to-write-to-file".getBytes();
Files.write(file, buf);
These methods take care of most of the work for you, such as opening and closing the stream, but are not intended for handling large files.
Writing larger File by Using Buffered Stream I/O (1.7)
The java.nio.file package supports channel I/O, which moves data in buffers, bypassing some of the layers that can bottleneck stream I/O.
String s = "much-larger-text-to-write-to-file";
try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
writer.write(s, 0, s.length());
}
This approach is preferential due to its efficient performance especially when completing a large amount of write operations. Buffered operations have this effect as they aren’t required to call the operating system’s write method for every single byte, reducing on costly I/O operations.
Using NIO API to copy (and create a new one) a file with an Outputstream (1.7)
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);
}
There are also additional methods that allow to copy all bytes from an input stream to a file.
FileWriter (text) (<1.7)
Writes directly into file (less performance) and should be used only when number of writes are less. Used to write character-oriented data to a file.
String s= "some-text";
FileWriter fileWriter = new FileWriter("C:\\path\\to\\file\\file.txt");
fileWriter.write(fileContent);
fileWriter.close();
FileOutputStream (binary) (<1.7)
FileOutputStream is meant for writing streams of raw bytes such as image data.
byte data[] = "binary-to-write-to-file".getBytes();
FileOutputStream out = new FileOutputStream("file-name");
out.write(data);
out.close();
With this approach one should consider to always write an array of bytes rather than writing one byte at a time. The speedup can be quite significant - up to 10 x higher or more. Therefore it is recommended to use the write(byte[]) methods whenever possible.