I'm writing a logger to my java program (in csv format) with bufferedWriter and FileWriter.
When i open the csv file while the program is running and continues writing to the file, I got this exception: "The process cannot access the file because it is being used by another process".
What i want is when i open the csv file while the program is running, The csv file will open in read mode and the program will writing successfully to the file.
I solved it by changing the closing of bufferedWriter and FileWriter to .flush() instead of .close()
Original minimal logger code (with the original close function)
public class logger {
private BufferedWriter bw = null;
private FileWriter fw = null;
private File file = null;
logger(String nclass) {
path = "c:\\test\\test.csv";
this.file = new File(path);
// Check if the file is already exist.
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
}
public void writeToFile(String msg) {
entryWrite();
try {
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
fw.append(msg);
} catch (IOException e) {
e.printStackTrace();
} finally {
close();
exitWrite();
}
}
}
private void close() {
try {
if (bw != null) {
bw.close();
bw = null;
}
if (fw != null) {
fw.close();
fw = null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
My solution function
private void close() {
try {
if (bw != null) {
bw.flush();
bw = null;
}
if (fw != null) {
fw.flush();
fw = null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
Now my answer is if it is ok not to close the stream and just use with flush?
Can there be any problems later? Because in all my tests its run well.
Thanks !!
Would it be ok some honesty?, in a very humble way. Sorry but stinky code:
why setting to null "bw" and "fw"?, globals?, why?
"ex.printStackTrace();" ? really?, no log4j or alike?
why not using a finally block?, what happens if an exception occurs while reading writing the file?
Someone has already answered this, for code refer to this excellent answer:
Is it necessary to close a FileWriter, provided it is written through a BufferedWriter?
Just do bufferedWriter object close.
bw.close();
say, you have a large file.txt.
Now u are gonna take something from a file and make a new smaller text file each time.
in that case,
somehow you have to write some lines of code to determine when you finish writing on a particular file. Then use flag to write bw.close();
eventually, you have to initialize the second file and do your task. then bw.close();
if you don't write fw.close(), then the file will be empty.
so, make sure each file writing operation you have to write bw.close()
Related
I'm writing and reading from a file and it works perfectly fine. However when the activity is switched or the app is closed it appears that the file is deleted or some such as null is returned when trying to read from the file. I believed it may be because I have an onCreate blank write to the file but that should only run upon the launch to make sure the file is created. I don't mind if the file doesn't persist between launches however it should at least persist between activities.
//in oncreate is writeToHistory("");
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}
public void btnAnsClicked(View v) throws IOException {
File path = getApplicationContext().getFilesDir();
File file = new File(path,"JWCalcHistory.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String oldAns = br.readLine();
if (!(oldAns.equals("null") || oldAns.equals(""))) {
if (Character.isDigit(readableSum.charAt(readableSum.length() - 1))) {
oldAns = "*" + oldAns;
}
UpdateSum(oldAns);
}
}
If someone can point out a way to make the contents of the file persist always until it is programmatically deleted or cleared then please let me know. The file doesn't already exist and is created upon the code being run.
You need to check if the file exists first. Something like this:
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
if(file.exists()) return;
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}
I am trying to write a code that will generate code into an already existing HTML File. It seems like I can not reach the existing HTML file in my repository.
I would be happy if someone could help.
Here is the method that should do the code generation:
public static void generate() {
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter("<filename>.html"))); //and path
pWriter.println("<code we want to put in>");
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null){
pWriter.flush();
pWriter.close();
}
}
}
Check your file read and write access. If you use Mac-OS or linux try to execute chmod 666 .html
If you use Java SE 7+, you can use try-with-resources with PrintWriter.
Check the path to your file.
Try this code below:
public static void generate() {
try (PrintWriter pWriter = new PrintWriter(new File("test.html"))){
pWriter.println("<CODE>");
pWriter.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
I'm currently working on a JavaFX application that uses a save file to load information about the previous session. I am having problems closing my BufferedReader and BufferedWriters. Files are not being unlocked until the JavaFX application is terminated. I have traced through the code and to ensure that there are no BufferedReaders and BufferedWriters left un-closed. If I try to modify the files after JavaFX is closed, they will be renamed and deleted correctly. Here's an example of one of my methods for reading and writing to files.
This is a school assignment and external libraries are not allowed.
public static boolean addNewAccount(User user, String fileName)
{
try
{
File output = new File("temp.csv");
File input = new File(fileName);
if (output.exists())
{
output.delete();
output.createNewFile();
}
BufferedWriter outputStream = new BufferedWriter(new FileWriter(output.getName()));
BufferedReader inputStream = new BufferedReader(new FileReader(input.getName()));
...
Read and write stuff here.
...
inputStream.close();
inputStream = null;
outputStream.close();
outputStream = null;
System.gc();
input.delete();
if (!output.renameTo(input))
{
HistoryLog.getInstance().log("Something is preventing a file from being closed.");
return false;
}
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
I am trying to write to a file and then read from that same file. The output is "Error: I/O exception". Meaning that the program is catching the IOException.
public class fileIO {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
File file = new File("io.txt");
BufferedReader read = new BufferedReader(new FileReader(file));
BufferedWriter write = new BufferedWriter(new FileWriter(file));
String needs = "This is going to the file";
write.write(needs);
String stuff = read.readLine();
while(stuff != null)
{
System.out.println(stuff);
stuff = read.readLine();
}
}
catch(IOException e)
{
System.out.println("Error: I/O Exception");
}
catch(NullPointerException e)
{
System.out.println("Error: NullPointerException");
}
}
}'
You cannot read from and write to the file at the same time, this will throw an IOException. You should close anything that has access to the file before trying to access it with something else. Invoking the close() method on BufferedWriter before trying to access the file with BufferedReader should do the trick.
EDIT: Also, as others have mentioned, you can use e.printStackTrace() to see where an exception has occurred in your program, which greatly helps when debugging.
EDIT: As zapl clarified, this is the case for some file systems, including Windows, but not all. It was my assumption that you were using a file system that restricts this as it seemed like the most likely problem.
I moved the BufferedReader to after where I closed the the BufferedWriter and that did the trick. thanks for the help.
public class fileIO {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
File file = new File("io.txt");
BufferedWriter write = new BufferedWriter(new FileWriter(file));
String needs = "This is going to the file";
write.write(needs);
write.close();
BufferedReader read = new BufferedReader(new FileReader(file));
String stuff = read.readLine();
while(stuff != null)
{
System.out.println(stuff);
stuff = read.readLine();
}
read.close();
}
catch(IOException e)
{
System.out.println("Error: I/O Exception");
e.printStackTrace();
}
catch(NullPointerException e)
{
System.out.println("Error: NullPointerException");
e.printStackTrace();
}
}
}
I have this code to write to a file when I add a user to an array list. The code works fine:
public void writeToFile(String content)
{
try {
File file = new File("H:/JavaWorkspace/TradingPlatformProject/User_Report.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
}
}
I want to write to a separate file when a user does something differently (say, request a permission upgrade). Is there any way I can write to a new file "UserRequests.txt" without duplicating this code?
Why not make the method more general?
public void writeToFile(String content, String fileName, String path)
{
try {
File file = new File(path + fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
}
}
Then you could use the method for writing all kinds of files :3
You should probably just use a 2nd argument, as in the following.
Moreover, you should close your Writers in a finally block. That way, you would be sure that the Writers are closed even if a exception occurred while writing.
public void writeToFile(String content, String path)
{
FileWriter fw
BufferedWriter bw
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
} finally {
bw.close();
fw.close();
}
}
I would just pass in the file you want to write to:
public void writeToFile(String content, String filename){
And then:
File file = new File("H:/JavaWorkspace/TradingPlatformProject/"+filename);