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();
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 have this method that takes one String and writes it to a file. I set the PrintWriter to true because I want to save all the data that is written to it.
I want to have headings on this file. How can I write the headlines to the file and only do it one time?
My method looks like this:
public static void writeToFile(String text) {
try {
File f = new File("test.txt");
FileWriter writer = new FileWriter("test", true);
writer.write(text);
writer.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
It's not clear whether your file has multiple heading or not. Assuming your file has only one heading we can do this as follow -
1. Since your file contain heading only one time, you can check whether the file is accessing for the first time -
File f = new File(//your file name);
if(f.exists() && !f.isDirectory()) {
//write heading
}
2. If the file is first time accessed then you can add a header -
String heading = "Some heading";
The full code looks like -
public static void writeToFile(String text) {
String heading = "Some heading";
try {
File f = new File("test.txt");
FileWriter writer = new FileWriter(f, true);
if(f.exists() && !f.isDirectory()) {
writer.write(heading);
}
writer.write(text);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}finally{
writer.close();
}
}
You can use BufferWriter to write a sentence and take a look at a better way to handle the file.
try {
String content = "This is the content to write into file";
File f = new File("test.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();
}finally{
writer.close();
}
}
I tried to make a console app that creates a file and writes text to it. What did I do wrong here?
package Writer;
import java.util.*;
import java.io.*;
public class main {
public static void main(String args[]) {
System.out.println("What would you like your SimpleText file name to be?");
Scanner uInputName = new Scanner(System.in);
String fileName = uInputName.nextLine();
File file = new File(fileName);
FileWriter fw = FileWriter;
BufferedWriter Text = new BufferedWriter(fw);
{
System.out.println("What would you like to write in: " + fileName);
Scanner uInputText = new Scanner(System.in);
String fileText = uInputText.nextLine();
fw.write(fileText);
Text.newLine();
}
System.out.println("Okay. File saved.");
}
This is totally illegal
FileWriter fw = FileWriter;
You probably want this
BufferedWriter Text = new BufferedWriter(new FileWriter(file));
You have an unnecessary code block
{
}
Your code is going to throw an IOExcpeption, so you have two options. Either
public static void main(String[] args) throws IOException {
}
Or
try {
BufferedWriter Text = new BufferedWriter(new FileWriter(file));
....
Text.write(inputText);
Text.close();
} catch (IOException ex) {
ex.printStackTrace();
}
First, let us begin with FileWriter fw.
fw should be a FileWriter object and so, you need to create a FileWriter object.
FileWriter fw = new FileWriter(file);
Now, notice that you may want to be more specific so it's worth checking the different constructors in the FileWriter API
Also, the writing won't THROW and exception, it MIGHT THROW an exception (saying that it will throw an exception is saying that your code will always fail and in that case, exception handling is "patching" it.
So I would recommend adding a catch clause. However, remember that YOU must ALWAYS close the writers yourself (Java does not do that unless specified otherwise) and so, you need to either try with resource
try (FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw)){
....
writer.write(inputText);
} catch (IOException ex) {
ex.printStackTrace();
}
or, add a finally clause
FileWriter fw = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(fw);
try {
....
writer.write(inputText);
} catch (IOException ex) {
ex.printStackTrace();
} finally{
writer.close();
fw.close();
}
Because the garbage collector does not close streams and if the exception is thrown inside the try then it will not reach the close() command but instead go to catch (and then finally) without closing the stream.
As others have said. it is difficult to know all the things that are wrong without knowing what exactly you are trying to accomplish.
And again, as PopoFibo mentioned, the thing that probably stands out most and seems to be syntactically incorrect is:
FileWriter fw = FileWriter;
So instead of listing what might be wrong, here is an example that might help you.
In first line you you enter in console you specify the file name - like you seem to want to do.
Each subsequent line you input into console is written to that file. Entering empty line will terminate the input.
public class Program {
public static void main(String[] args) {
System.out.println("Enter file name:");
Scanner input = new Scanner(System.in);
String fileName = null;
while (fileName == null) {
if (input.hasNextLine()) {
fileName = input.nextLine();
}
}
try {
FileWriter fw = new FileWriter(fileName);
String newLine = System.getProperty("line.separator");
System.out.println("Enter lines (enter empty line to terminate):");
String line = null;
while (true) {
if (input.hasNextLine()) {
line = input.nextLine();
if (isTerminatingEntry(line)) {
break;
}
fw.write(line + newLine);
}
}
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
input.close();
}
private static boolean isTerminatingEntry(String line) {
// add some condition that will cause you to stop reading input
// in this example, empty line will terminate the input
return line.length() == 0;
}
}