Veracode CWE ID 404 Improper Resource Shutdown or Release - java

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) {
}

Related

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

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

Android Java Read and Save data doesnt work

Hey I would like to save datas and then I would like to read them and put them in a EditText
speichern.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
save();
tv.setText("gespeichert");
}
});
private void save() {
try {
File myFile = new File("bla.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(string.toString() + "\n");
myOutWriter.append(string2.toString());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Gespeichert",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
private void read() {
int bla;
StringBuffer strInhalt = new StringBuffer("");
try {
FileInputStream in = openFileInput("bla.txt");
while( (bla = in.read()) != -1)
strInhalt.append((char)bla);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
What can i change?`
pelase help me
I'm usin eclipse
And i would like to safe the .txt not external.
I don't believe you are creating your file correctly:
File file = new File("test.txt");
file.createNewFile();
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write("Hello World");
fo.close();
System.out.println("file created: "+file);
url = upload.upload(file);
}
And to read this file:
try {
// open the file for reading
InputStream instream = openFileInput("test.txt");
// if file the available for reading
if (instream) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (( line = buffreader.readLine())) {
// do something with the settings from the file
}
}
// close the file again
instream.close();
} catch (java.io.FileNotFoundException e) {
// do something if the myfilename.txt does not exits
}
And don't forget to encapsulate code with a try-catch block to catch an IOException which is thrown from these objects.
EDIT
Add this to your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
or...
File filesDir = getFilesDir();
Scanner input = new Scanner(new File(filesDir, filename));
Hope that helps! :)

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