Android BufferedWriter : Empty File Saved. - java

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

Related

Veracode CWE ID 404 Improper Resource Shutdown or Release

I have this code:
try {
BufferedWriter bw = null;
FileWriter fw = null;
try {
final String fileName = getFileName();
File propertiesFile=new File(getFilesDir(), fileName);
fw = new FileWriter(propertiesFile);
bw = new BufferedWriter(fw);
bw.write(s);
File file = new File(getFilesDir(), fileName);
} catch (IOException e) {
}finally{
if(bw != null){
bw.close();
}
if(fw != null){
fw.close();
}
if(bw != null){
bw.close();
}
}
} catch (Exception e) {
}
Veracode detected a flaw (Improper Resource Shutdown or Release ) on this line bw.write(s);
How to fix this?
Thanks in advance
Use try-with-resources starting java 7
try (FileWriter fw = new FileWriter(propertiesFile);
BufferedWriter bw = new BufferedWriter(fw)){
......
}catch (Exception e){}
Using try finally fix the flaw, and inside finally close the BufferedWriter and the FileWriter
try {
BufferedWriter bw = null;
FileWriter fw = null;
try {
final String fileName = getFileName();
File propertiesFile=new File(getFilesDir(), fileName);
fw = new FileWriter(propertiesFile);
bw = new BufferedWriter(fw);
bw.write(s);
File file = new File(getFilesDir(), fileName);
}finally{
if(bw != null){
bw.close();
}
if(fw != null){
fw.close();
}
}
} catch (Exception e) {
}

Renaming file to existing file java

I am trying to
Create Temp File "Temp Account Info.txt"
Write information from existing Account File "Account Information.txt" TO "Temp Account Info.txt"
Omit certain information
Delete "Account Information.txt"
Rename "Temp Account Info.txt" to "Account Information.txt"
My issue is steps 4 and 5. Nor am I sure if I am ordering it correctly.
The code is provided below.
public static void deleteAccount(String accountNumber) throws Exception {
File accountFile = new File("Account Information.txt");
File tempFile = new File("Temp Account Info.txt");
BufferedReader br = new BufferedReader(new FileReader(accountFile));
FileWriter tempFw = new FileWriter(tempFile, true);
PrintWriter tempPw = new PrintWriter(tempFw);
String line;
try {
while ((line = br.readLine()) != null) {
if(!line.contains(accountNumber)) {
tempPw.print(line);
tempPw.print("\r\n");
}
}
**FileWriter fw = new FileWriter(accountFile);
PrintWriter pw = new PrintWriter(fw);
tempFile.renameTo(accountFile);
accountFile.delete();
fw.close();
pw.close();
tempFw.close();
tempPw.close();
} catch (Exception e) {
System.out.println("ERROR: Account Not Found!");
}
}
The full code can be found at: https://hastebin.com/eposapecep.java
Any help would be greatly appreciated!
I am aware that I do not correctly check for "Account Not Found" and will try to figure this out after the naming issue.
Thanks in advance!
Use the renameTo() method of File.
try {
File file = new File("info.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String str = br.readLine();
File file2 = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(file2));
bw.write(str);
br.close();
bw.close();
if (!file.delete()) {
System.out.println("delete failed");
}
if (!file2.renameTo(file)) {
System.out.println("rename failed");
}
} catch (IOException ex) {
ex.printStackTrace();
}
The code above reads the first line of info.txt, writes it to temp.txt, deletes info.txt, renames temp.txt to info.txt

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.

Concurrent Modification Exception while using FileWriter

I am trying to create 4 index files using FileWriter. However this code throws Concurrent Modification Exception. I searched a few forums and found the use of finally as a solution, which dint work. Please tell me where can the error be.
public synchronized void writeToDisk() throws IndexerException {
// TODO Implement this method
BufferedWriter bw = null;
try {
//System.out.println("entering writeToDisk");
File file = new File("/Users/workspace/master/tmp//Index.txt");
if(IndexAuthor==-1){
file = new File("/Users/workspace/master/tmp/Author.txt");
if (!file.exists()) {
file.createNewFile();
}
}
if(IndexTerm==-1){
file = new File("/Users/workspace/master/tmp/Term.txt");
if (!file.exists()) {
file.createNewFile();
}
}
if(IndexCategory==-1){
file = new File("/Users/workspace/master/tmp/Category.txt");
if (!file.exists()) {
file.createNewFile();
}
}
if(IndexLink==-1){
file = new File("/Users/workspace/master/tmp/Link.txt");
if (!file.exists()) {
file.createNewFile();
}
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(PostingsList.toString());
//bw.close();
//System.out.println("Done");
} catch (IOException e) {
//do nothing
}
finally
{
try {
if (bw == null)
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Writing to multiple files without duplicating code 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);

Categories

Resources