BufferedWriter is not writing text to text file - java

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

Related

program does not work properly when moved to Servlet

I have made a program that works perfectly well in java class.. but when I moved my code to a servlet it does not work as expected
the program creates some files writes to them then later reads from them.. the problem is when I move the code to servlet the program would not create files in the first place, so when later reading them it will give FileNotFound exception
this is how I create write to and read from files.
first, create file and write to it
...
Writer output = null;
File file = new File(i + ".txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
... then later read from file
File file = new File(i+".txt");
Scanner br = new Scanner(file);
// BufferedReader br = new BufferedReader(new FileReader(new File(TDM.class.getResource(i + ".txt").getPath())));
while (br.hasNextLine()) {
line = br.nextLine();
...
Notes:
*the above code is NOT in servlet.. servlet only CALL the method that contains this code.
*apparently, the PROBLEM is with creating the file.. for some reason the file is not created when the method is called from servlet. how ever it works perfectly when called from another java class.
thanks in advance
Use a path: File.createTempFile for temporary files, or convert a web path ("/.../...") relative to your web contents into a file system File:
File file =
request.getServletContext().getRealPath("/WEB-INF/files/" + i + ".txt");
file.getParentFile().mkdirs();
...
Better yet give URLs to a file, that will be delivered by a Servlet streaming the file to
response.setContentType("text/plain");
response.getOutputStream();
...
If you write resource "files," that may reside in a .war of .jar; then do not use File.
Read them using an InputStream:
InputStream in = getClass().getResource("/...").getResourceAsStream();
And copy them to the response.getOutputStream().
Also do not use the utility "short-hand" class FileWriter as it uses the platform encoding, which on Windows is some ANSI encoding and on Linux servers in general is UTF-8.
new BufferedWriter(new OutputStreamWriter
(new FileOutputStream(file), "UTF-8"));
this comment from "Elliott Frisch" solved my problem
"You need to specify a path to your files."
simply I had to provide the "absolute" path instead of relative path
so, the code should be like this
Writer output = null;
File file = new File("/file/path/"i + ".txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
and
File file = new File("/file/path/"i+".txt");
Scanner br = new Scanner(file);
// BufferedReader br = new BufferedReader(new FileReader(new File(TDM.class.getResource(i + ".txt").getPath())));
while (br.hasNextLine()) {
line = br.nextLine();
then when I had this exception java.lang.NoClassDefFoundError: org/jsoup/Jsoup I just had to downlad the jsoup library from the internet and add it to my project under (library folder).
thank you very much for you all :)

Before creating the file , deleting the file of previous day

I am creating a dat file in C: drive folder named abc as shown below , Now my file is generated everyday
now suppose if my file is generated today, then tommrow it will be also generated as usual
but when tommrow it is generated I have to make sure that earlier day file is deleted as the space in that folder is limited and this check is every time need to be done previos day file to be get deleted from that folder , please advise how to achieve this..
File file = new File(FilePath + getFileName()); //filepath is being passes through //ioc //and filename through a method
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(
file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
fileOutput));
why not use file.delete() ?
File file = new File(FilePath + getFileName()); //filepath is being passes through //ioc //and filename through a method
if (file.exists()) {
file.delete(); //you might want to check if delete was successfull
}
file.createNewFile();
FileOutputStream fileOutput = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutput));
If your file name same in time to time no need to delete that. By running your code tomorrow, will over write file created today.
Consider following case
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\Test\test.txt"));
bw.write("abbbb");
bw.close(); // now this will create a test.txt in side Test folder
now run this by change writing String
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\test.txt"));
bw.write("hihi");
bw.close(); // now you can see file only containing hihi
You can change your code this way:
if (file.exists()) {
file.delete();
}
file.createNewFile();
And if it does not work, it's a matter of permission.
If you are using Java 7 then there is standard way to get file creation time, So that you can check if file is created in previous day and should be delete.
Path path = Paths.get("/filepath/");
BasicFileAttributes fileAttributes = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("creationTime:"+ fileAttributes.creationTime());

Appending Byte[] to end of a binary file

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.

save file with JFileChooser save dialog

I have written a Java program that opens all kind of files with a JFileChooser. Then I want to save it in another directory with the JFileChooser save dialog, but it only saves an empty file. What can I do for saving part?
Thanks.
JFileChooser just returns the File object, you'll have to open a FileWriter and actually write the contents to it.
E.g.
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
FileWriter fw = new FileWriter(file);
fw.write(contents);
// etc...
}
Edit:
Assuming that you simply have a source file and destination file and want to copy the contents between the two, I'd recommend using something like FileUtils from Apache's Commons IO to do the heavy lifting.
E.g.
FileUtils.copy(source, dest);
Done!
Just in addition to Kris' answer - I guess, you didn't read the contents of the file yet. Basically you have to do the following to copy a file with java and using JFileChooser:
Select the source file with the FileChooser. This returns a File object, more or less a wrapper class for the file's filename
Use a FileReader with the File to get the contents. Store it in a String or a byte array or something else
Select the target file with the FileChooser. This again returns a File object
Use a FileWriter with the target File to store the String or byte array from above to that file.
The File Open Dialog does not read the contents of the file into memory - it just returns an object, that represents the file.
Something like..
File file = fc.getSelectedFile();
String textToSave = mainTextPane.getText();
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter(file));
writer.write(textToSave);
JOptionPane.showMessageDialog(this, "Message saved. (" + file.getName()+")",
"ImPhil HTML Editer - Page Saved",
JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException e)
{ }

Java FileWriter overwrite

I have a piece of code that generates new data whenever there is new data available as InputStream . The same file is overwritten everytime. Sometimes the file becomes 0 kb before it gets written. A webservice reads these files at regular intervals. I need to avoid the case when the file is 0 bytes.
How do it do this? Will locks help in this case? If the browser comes in to read a file which is locked, will the browser continue to show old data from the cache until the lock is released and file is available to be read again.
try{
String outputFile = "output.html";
FileWriter fWriter = new FileWriter(outputFile);
//write the data ...
fWriter .flush();
outputFile = "anotheroutput.html";
fWriter = new FileWriter(outputFile);
//write the data ...
fWriter .flush();
fWriter.close();
}
catch(Exception e)
{
e.prinStackTrace();
}
Try writing to a temporary file (in the same file system) and once the file write is complete move it into place using File.renameTo(). If you underlying file system supports atomic move operations (most do) then you should get the behaviour that you require. If you are running on windows you will have to make sure you close the file after reading otherwise the file move will fail.
public class Data
{
private final File file;
protected Data(String fileName) {
this.file = new File(filename);
}
/* above is in some class somehwere
* then your code brings new info to the file
*/
//
public synchronized accessFile(String data) {
try {
// Create temporary file
String tempFilename = UUID.randomUUID().toString() + ".tmp";
File tempFile = new File(tempFilename);
//write the data ...
FileWriter fWriter = new FileWriter(tempFile);
fWriter.write(data);
fWriter.flush();
fWriter.close();
// Move the new file in place
if (!tempFile.renameTo(file)) {
// You may want to retry if move fails?
throw new IOException("Move Failed");
}
} catch(Exception e) {
// Do something sensible with the exception.
e.prinStackTrace();
}
}
}
FileWriter fWriter = new FileWriter(fileName,true);
try using above :-)
Your requirement is not very clear. Do you want to write a new name file every time or you want to append to the same file or you want to over write the same file? Anyway all three cases are easy and from the API you can manage it.
If the issue is that a web service is reading the file which is not yet complete i.e. is in writing phase. In your web service you should check if the file is read only, then only you read the file. In writing phase once writing is finished set the file to read only.
The 0Kb file happens because you are overwriting the same file again. Overwriting cleans up all the data and then start writing the new content.
public class Data
{
String fileName;
protected Data(String fileName)
{
this.fileName= fileName;
return; // return from constructor often not needed.
}
/* above is in some class somehwere
* then your code brings new info to the file
*/
//
public synchronized accessFile(String data)
{
try
{
// File name to be class member.
FileWriter fWriter = new FileWriter(fileName);
//write the data ...
fWriter.write(data);
fWriter .flush();
fWriter .close();
return;
}
catch(Exception e)
{
e.prinStackTrace();
}
this is not needed:
outputFile = "anotheroutput.html";
fWriter = new FileWriter(outputFile);
//write the data ...
fWriter .flush();
fWriter.close();
that's because work on the file is a method of class Data

Categories