I'm parsing a file. I'm creating a new output file and will have to add the 'byte[] data' to it. From there I will need to append many many other 'byte[] data's to the end of the file. I'm thinking I'll get the user to add a command line parameter for the output file name as I already have them providing the file name which we are parsing. That being said if the file name is not yet created in the system I feel I should generate one.
Now, I have no idea how to do this. My program is currently using DataInputStream to get and parse the file. Can I use DataOutputStream to append? If so I'm wondering how I would append to the file and not overwrite.
If so I'm wondering how I would append to the file and not overwrite.
That's easy - and you don't even need DataOutputStream. Just FileOutputStream is fine, using the constructor with an append parameter:
FileOutputStream output = new FileOutputStream("filename", true);
try {
output.write(data);
} finally {
output.close();
}
Or using Java 7's try-with-resources:
try (FileOutputStream output = new FileOutputStream("filename", true)) {
output.write(data);
}
If you do need DataOutputStream for some reason, you can just wrap a FileOutputStream opened in the same way.
Files.write(new Path('/path/to/file'), byteArray, StandardOpenOption.APPEND);
This is for byte append. Don't forget about Exception
File file =new File("your-file");
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(your-string);
bufferWritter.close();
Of coruse put this in try - catch block.
Related
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 4 years ago.
I am new to File Streams and would appreciate some help. The following code is the code I use to write to a specified file.
OutputStream outStream = new FileOutputStream(file);
outStream.write(contentsToWrite.getBytes());
outStream.close();
How do I save different lines to a file? In my case using \n does not work when writing to a file.
How do I save a line to the file without deleting the other lines?
There is a nice, simple method which allows you to do this with a List of Strings you want to write and the file itself.
List<String> lines=new ArrayList<>(contentToWrite);//if it is an array or something that isn't a list
Files.write(file.toPath(),lines);
Java has some wrapper class to file streams. BufferedWriter can be used to write string to file.
boolean append = true;
String filename = "/path/to/file";
BufferedWriter writer = new BufferedWriter(new FileWriter(filename, append));
// OR: BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename, append)));
writer.write(line1);
writer.newLine();
writer.write(line2);
writer.newLine();
// ......
writer.close();
append meanings you write to the end of the file instead of empty the file.
The FileOutputStream class constructor method has the second parameter. if you set it to true. It will append the content the file you write. And "\r\n" can change to a new line.
OutputStream outStream = new FileOutputStream("a.txt",true);
outStream.write("hello".getBytes());
outStream.write("\r\n".getBytes());
outStream.write("hello".getBytes());
outStream.close();
I have a BufferedWriter which is being used to write to a file which has just been created in the given directory, however, for some reason it is not writing the text that it reads from another file, here is my code:
private static final String tempFileDir = System.getProperty("user.dir") + "/TempATM.txt";
File tempFile = new File(tempFileDir); //Create temporary file to write new info to
File toRenameTo = new File("VirtualATM.txt"); //filename to rename temp file to
if (!tempFile.exists() && !tempFile.isDirectory()) {
tempFile.createNewFile(); //Create temp file if it doesn't already exist.
}
FileOutputStream fos = new FileOutputStream(tempFile, true); //For writing new balance
Writer bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));//For writing new balance
String newLineRead = null;
FileReader fileReader = new FileReader("VirtualATM.txt");//for reading from file
BufferedReader newBufferedReader = new BufferedReader(fileReader);//for reading from file
while((newLineRead = newBufferedReader.readLine()) != null){
if(!newLineRead.contains(cardNumberStr)){
bw.append(newLineRead); //If the line does not contain user entered card number, write line to new file.
((BufferedWriter) bw).newLine();
}else if(newLineRead.contains(cardNumberStr)){
bw.append(newAccountDetails); //Write updated account details if the line read contains users account number
((BufferedWriter) bw).newLine();
}
}
File toDeleteFile = new File("dirToWriteFile"); //File path to delete the file.
if(!toDeleteFile.delete()){
JOptionPane.showMessageDialog(null, "FATAL ERROR! Could not delete VirtualATM.txt", "Error", JOptionPane.ERROR_MESSAGE); // for if there is an error when deleting file
}
if(!file.renameTo(toRenameTo)){
JOptionPane.showMessageDialog(null, "FATAL ERROR! Could not rename the file to VirtualATM.txt", "Error", JOptionPane.ERROR_MESSAGE);//for if there is an error renaming file
}
Edit:
I am also having trouble deleting and renaming the text file, could any suggest what may be causing this problem, what SecurityExceptions etc. may be preventing Java from deleting and renaming a text file (.txt) on Windows 8.1?
You need to either flush the buffer post writing the data to buffer like
bw.flush();
or close the writer like
bw.close();//handle exception if you are not using AutoCloseable feature.
You must either flush the buffer to the disk after writing the data using:
bw.flush();
or / and if you have finished writing the data, you must always close the writer which will automatically flush the data to the disk before closing using:
bw.close();
Hope this helps. Good luck and have fun programming!
Cheers,
Lofty
public void save() throws IOException {
File f = new File(path);
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
FileOutputStream fout = new FileOutputStream(f, false);//overwrite, append set to false
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(this.vehicles);
out.close();
}
I Have the following code that saves an object of type vehicule into a file. However, I don't understand quite well how it works since it was a sample provided for me, and since I am new in the java field.
I am wondering what is the interpretation of these lines if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
} I am wondering what getParentFile().exists() does and why are we searching for the parent file while we are interested in the file itself. same question for the next line: why are we interested in the parent directory when we are going to create the file?
I would like to know also the difference between FileOutputStream and ObjectOutputStream and why both are used one next to another in the following lines FileOutputStream fout = new FileOutputStream(f, false);//overwrite, append set to false
ObjectOutputStream out = new ObjectOutputStream(fout);
Thank you in advance
Files are pointers to file or directory locations on a File System. If you intend to write to a file, though, the parent directory in which it will reside must exist. Otherwise, you'll get an IOException. The mkdirs call will create the necessary parent directory (or directories) to avoid that IOException.
I don't think the exists check is really necessary, though, since the mkdirs method returns false if it actually didn't create anything.
Also, you should close your OutputStream within a finally block or use the Java 7 try-with-resources:
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f, false))) {
out.writeObject(vehicles);
}
I've been working on sort of "logging" to text file using BufferedWriter and I came across a problem:
I run the following code.. fairly basic..
BufferedWriter out = new BufferedWriter(new FileWriter(path+fileName));
String str = "blabla";
out.write(str);
out.close();
and the next thing I know is that the entire file that had couple of lines of text has been cleared and only 'blabla' is there.
What class should I use to make it add a new line, with the text 'blabla', without having to get the entire file text to a string and adding it to 'str' before 'blabla'?
What class should I use to make it add a new line, with the text 'blabla', without having to get the entire file text to a string and adding it to 'str' before 'blabla'?
You're using the right classes (well, maybe - see below) - you just didn't check the construction options. You want the FileWriter(String, boolean) constructor overload, where the second parameter determines whether or not to append to the existing file.
However:
I'd recommend against FileWriter in general anyway, as you can't specify the encoding. Annoying as it is, it's better to use FileOutputStream and wrap it in an OutputStreamWriter with the right encoding.
Rather than using path + fileName to combine a directory and a filename, use File:
new File(path, fileName);
That lets the core libraries deal with different directory separators etc.
Make sure you close your output using a finally block (so that you clean up even if an exception is thrown), or a "try-with-resources" block if you're using Java 7.
So putting it all together, I'd use:
String encoding = "UTF-8"; // Or use a Charset
File file = new File(path, fileName);
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file, true), encoding));
try {
out.write(...);
} finally {
out.close()'
}
Try using FileWriter(filename, append) where append is true.
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//oh noes!
}
The above should work: Source Reference
I'm making a program that will output lines to a text file. I don't wish to overwrite the file, but that is what my current code does. I just want to go down the number of lines that are already there and write hello. Here is my code:
FileWriter fileWriter = new FileWriter(fileLocation, false);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
while(numberOfLines > compareToNumOfLines) {
bufferedWriter.newLine();
compareToNumOfLines++;
}
bufferedWriter.write("hello");
bufferedWriter.close();
Unfortunately, this just creates spaces where the text used to be. What am I doing wrong?
Change
FileWriter fileWriter = new FileWriter(fileLocation, false);
to
FileWriter fileWriter = new FileWriter(fileLocation, true);
As explained in the documentation, the second argument is a boolean that specify if you want to append the text or overwrite it.
If you want to append text to existing file then open the file in append mode. If you want to write at random place in file then you can use RandomAccessFile class.