Writing to multiple files without duplicating code Java - java

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);

Related

Write to File doesn't persist between activities

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();
}
}

Android BufferedWriter : Empty File Saved.

I am facing a problem and unable to identify it. The case is, I have an activity from which I am saving a JSON file to the storage on some button click. There are times when the file is an empty file(0 KB). So, most of the times it work as expected but this 0 KB file created a headache. There is no exception at all.
Thanks in advance!
BufferedWriter bw = null;
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
bw = new BufferedWriter(new FileWriter(file, false));
bw.write(content);
} catch (Exception e) {
Logger.e(mContext,"Write To File",e.toString());
}
finally {
try {
if (bw != null) {
bw.close();
}
}catch (Exception e)
{
Logger.e(mContext,"Write To File",e.toString());
}
}
I had the same issue. Solved it that way:
fw = new FileWriter(file, false);
bw = new BufferedWriter(fw);
...
bw.flush();
bw.close();
fw.close();

Create multiple files

I have this code:
try {
File file = new File(something+counter+".txt");
counter++;
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
I need to make it like this: When they press enter, new file will be created in defined location (I made JTextField for this), but when they press it again, the file OVERWRITES. That's the problem. I need them to press enter - create new file: sample1.txt, press enter again, create new file: sample2.txt
OK by looking at your code now, it looks fine, but you probably declared the counter variable within the method. If so, it will be 'reset' to whatever you set it to every time the method is called.
EDIT:
This should work.
import java.io.*;
public class Example {
public static void main(String args[]) {
Example ex = new Example();
ex.writeFile();
ex.writeFile();
}
private void writeFile() {
try {
File file = new File("file" + counter + ".txt");
counter++;
System.out.println("Writing to " + file.toString());
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("content");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private int counter = 0;
}
I get
Writing to file0.txt
Writing to file1.txt
as output and both files have the string 'content' written in them.
EDIT2:
Call writefile whenever the user presses enter.

BufferedWriter do not write to a file

I am trying to make a text editor, but I am unable to save the contents to a text file : the file is created but empty.
class Saver implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
File file = new File("projekat");
if(!file.exists()){
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(tekst1);
bw.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
}
JTextArea code
area = new JTextArea(tekst1, 30,30);
tekst1 = area.getText();
Please help me. Best regards
The problem is that you need to call tekst1 = area.getText();
again in your actionPerformed method to update the contents of tekst1.
class Saver implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
File file = new File("projekat");
if (!file.exists()) {
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// get latest contents of the JTextArea
tekst1 = area.getText();
bw.write(tekst1);
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
bw.write(tekst1);
this line writes the content to the file.
you were close, the string you are writing is just empty, so it's normal that nothing writes to the file.
Some examples:
http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
http://www.tutorialspoint.com/java/io/bufferedwriter_write_string.htm
http://beginnersbook.com/2014/01/how-to-write-to-file-in-java-using-bufferedwriter/
include only this code :---
file.createNewFile();
in your if statement and place other things out of your if.

Java WriteFile can't see contents

I want to create a simple text file with some text in it.
import java.io.*;
class TextFileWriter{
public static void writeTextFile(String fileName, String s) {
FileWriter output = null;
try {
output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}
}
public static void main(String args[]){
writeTextFile("myText.txt","some text");
}
}
When i run this code i successfully create the text file but when i open it i don't see the contents ("some text"). What am I doing wrong?
You're closing underlying FileWriter but actual data are still stored (buffered) in BufferedWriter object. That's the object you have to close:
FileWriter output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
writer.flush(); // Good practice but not required
writer.close();

Categories

Resources