Close this "FileInputStream" sonar - java

I'm trying to adapt my code to Sonar and I don't get why I can't correct this blocker.
Its a 'Close this FileInputStream' with this starting code:
BufferedReader localBufferedReader = null;
try {
localBufferedReader = new BufferedReader( new InputStreamReader( new FileInputStream(inputFile),"UTF-8")); //THIS INPUTSTREAM!!
String line;
//
// Fill Hashmap
HashMap hmVar = (HashMap) this.context.getAttribute(this.hmVarName);
if (hmVar == null)
hmVar = new HashMap();
String[] props = new String[2];
while ((line = localBufferedReader.readLine()) != null) {
//Split line into key, value
if(line.startsWith("#"))
continue;
props = line.split("=");
hmVar.put(props[0], props[1]);
}
this.context.setAttribute(this.hmVarName, hmVar);
} catch (FileNotFoundException localException2) {
this.context.logError("Unable to find file: " + inputFile);
localException2.printStackTrace();
throw new WFException("Unable to find file: " + inputFile);
} catch (Exception localException4) {
this.context.logError("Exception reading file: " + inputFile
+ " (" + localException4.getMessage() + ")");
localException4.printStackTrace();
throw new WFException("Exception reading file: " + inputFile
+ " (" + localException4.getMessage() + ")");
} finally {
try {
if (localBufferedReader != null) {
localBufferedReader.close();
}
} catch (Exception localException5) {
}
}
So, ok. I declared apart the fileinputstream and go on, but it still doesn't like the way I close it.
BufferedReader localBufferedReader = null;
FileInputStream fis = null;
try {
//StringBuffer localStringBuffer = new StringBuffer();
fis = new FileInputStream(inputFile);
//localBufferedReader = new BufferedReader( new InputStreamReader( new FileInputStream(inputFile),"UTF-8")); SONAR correction FileInputStream needs to be closed
localBufferedReader = new BufferedReader( new InputStreamReader( fis,"UTF-8"));
String line;
//
// Fill Hashmap
HashMap hmVar = (HashMap) this.context.getAttribute(this.hmVarName);
if (hmVar == null)
hmVar = new HashMap();
String[] props = new String[2];
while ((line = localBufferedReader.readLine()) != null) {
//Split line into key, value
if(line.startsWith("#"))
continue;
props = line.split("=");
hmVar.put(props[0], props[1]);
}
this.context.setAttribute(this.hmVarName, hmVar);
} catch (FileNotFoundException localException2) {
this.context.logError("Unable to find file: " + inputFile);
localException2.printStackTrace();
throw new WFException("Unable to find file: " + inputFile);
} catch (Exception localException4) {
this.context.logError("Exception reading file: " + inputFile
+ " (" + localException4.getMessage() + ")");
localException4.printStackTrace();
throw new WFException("Exception reading file: " + inputFile
+ " (" + localException4.getMessage() + ")");
} finally {
try {
if (localBufferedReader != null) {
localBufferedReader.close();
}
if (fis != null) {
fis.close();
}
} catch (Exception localException5) {
}
}
Any ideas? I'm closing it the same way the BufferedReader that returns no issue.

Streams Readers and Writers implement the Closable interface. So you can get rid of the sonar warning if you use the try-with-resource construct:
try ( BufferedReader localBufferedReader = new BufferedReader( ...))
{
...
}
Any allocated Closable in the try (..) will be closed automatically if you leave the try block.

Related

BufferedReader.readline() returns null

BufferedReader returns null and i don't understand why.
I have a ClientServer app with GUI interface and it works good, but in this method
idk why in loop msgFromServer has value = null because br.readline() returns it.
try {
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter pw = new PrintWriter(sock.getOutputStream(), true);
pw.println("refreshRoomOnClient");
countClientInRoomFromServer = br.readLine();
lblCountClientInRoom.setText("Clients in the room: " + countClientInRoomFromServer);
pw.println(txtNameRoom.getText());
listModelRoom.removeAllElements();
int size_listModelRoom = listModelRoom.size();
String msgFromServ;
while (!"exit".equals(msgFromServ = br.readLine())) {
System.out.println(msgFromServ);
if ("Cant find File".equals(msgFromServ)) {
txtLogs.append("Can't find files" + "\n");
break;
} else if ("error".equals(msgFromServ)) {
txtLogs.append("Error reading" + "\n");
break;
}
listModelRoom.insertElementAt(msgFromServ, size_listModelRoom);
}
} catch (IOException ex) {
txtLogs.append("btnRefreshCountClientInRoomActionPerformed..." + "\n");
}

Issues with readLine

Just try to get the line right in the while statement
try {
FileReader fr = new FileReader("Original.txt");
BufferedReader br = new BufferedReader(fr);
String strFullName;
while ((strFullName = br.readLine()) != null) {
int intSpaceLocation = strFullName.indexOf(" ");
String strLastName = strFullName.substring(0, intSpaceLocation);
String strFirstName = strFullName.substring(intSpaceLocation + 1);
System.out.println("First Name = " + strFirstName + " Last Name = " + strLastName);
}
br.close();
fr.close();
} catch (Exception e) {
}
I am trying to get each line from a file and trying to split it with a space, but it only does it for the first line
Output:
First Name = Todd Last Name = Jackson

Debugging File Search / Merge Code

This program is meant to see two files located in a particular folder and then merge those two files and create a third file which is does. From the third merged file it is then searching for a keyword such as "test", once it finds that key word it prints out the location and the line of the keyword which is what is somewhat doing. What is happening is when I run the program it stops after the finds the keyword the first time in a line but it will not continue to search that line. So if there is multiple keyword 'test' in the line it will only find the first one and spit back the position and line. I want it to print both or multiple keywords. I think it is because of the IndexOf logic which is causing the issue.
import com.sun.deploy.util.StringUtils;
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class Concatenate {
public static void main(String[] args) {
String sourceFile1Path = "C:/Users/me/Desktop/test1.txt";
String sourceFile2Path = "C:/Users/me/Desktop/test2.txt";
String mergedFilePath = "C:/Users/me/Desktop/merged.txt";
File[] files = new File[2];
files[0] = new File(sourceFile1Path);
files[1] = new File(sourceFile2Path);
File mergedFile = new File(mergedFilePath);
mergeFiles(files, mergedFile);
stringSearch(args);
}
private static void mergeFiles(File[] files, File mergedFile) {
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, true);
out = new BufferedWriter(fstream);
} catch (IOException e1) {
e1.printStackTrace();
}
for (File f : files) {
System.out.println("merging: " + f.getName());
FileInputStream fis;
try {
fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
while ((aLine = in.readLine()) != null) {
out.write(aLine);
out.newLine();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void stringSearch(String args[]) {
try {
String stringSearch = "test";
BufferedReader bf = new BufferedReader(new FileReader("C:/Users/me/Desktop/merged.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file");
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
}
}
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
It's because you are searching for the word once per line in your while loop. Each iteration of the loop takes you to the next line of the file because you are calling bf.readLine(). Try something like the following. You may have to tweak it but this should get you close.
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
while(indexfound > -1)
{
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
indexfound = line.indexOf(stringSearch, indexfound);
}
}

File reading from controller

I have 2 almost identical methods. But 1 can see my file , another not.It skips the method body with line = null. Dont understand why.
This doesnt work
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFileUpload(#RequestParam("file") MultipartFile file, Model model) {
if (!file.isEmpty()) {
try {
String path = "d:/" + file.getOriginalFilename();
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(path)));
stream.write(bytes);
model.addAttribute("list", addRecordsToBD(path));
stream.close();
} catch (Exception e) {
log.error("Upload failed", e);
}
}
return "show";
}
private List addRecordsToBD(String path) {
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
while ((line = reader.readLine()) != null) {
String[] users = line.split(",");
repository.saveAndFlush(new User(users[0], users[1], users[2],
users[3], users[4]));
}
} catch (IOException e) {
System.out.println("Input problems");
}
System.out.println("Inserting done");
return repository.findAll();
}
But this work great
public void addRecordsToBD(String path) {
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
while ((line = reader.readLine()) != null) {
String[] users = line.split(",");
System.out.println("User [Name = " + users[0] +
", surname = " + users[1] +
" login = " + users[2] +
" mail = " + users[3] +
" phone = " + users[4] +
"]");
}
} catch (IOException e) {
System.out.println("Input problems");
}
System.out.println("Inserting done");
}
}
Can some one explain me, what's the problem and why this happened ?

Printing output in new line in java I/O files

i want to print the output in new line how to do this?
Below is the output.
CHILD: Child line one oneCHILD: Child line one twoCHILD: Child line one three
CHILD: Child line two oneCHILD: Child line two twoCHILD: Child line two three
here is my code for it...
try {
fis = new FileInputStream(file);
fileWriterChild = new FileWriter(outputFileForChild);
brChild = new BufferedWriter(fileWriterChild);
fr = new FileReader(file);
br = new BufferedReader(fr);
int child_line_no = 0;
int buffer = 0;
String currentLine = br.readLine();
while (currentLine != null) {
if (currentLine.contains("CHILD:")) {
Files.write(Paths.get("C:/output.child.txt"),
currentLine.getBytes(), StandardOpenOption.APPEND);
}
currentLine = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
fis.close();
}
}
Depends on what do you want to do. Here are my two ways:
Appending one line to the end of file
void WriteLog(String date, String message) {
String logFileName = <path to file>;
File logFile = new File(logFileName);
//make directories
logFile.getParentFile().mkdirs();
try (FileWriter writer = new FileWriter(logFile, true)) {
writer.write(message);
writer.write("\r\n");
} catch (IOException ex) {
Cls_log.LogError("Error writing log - " + ex.toString());
}
}
Writing all strings as lines to file (overwriting file)
public static void WriteABcardLog(Map<String,String> etiquetteCache) {
File logFile = new File(<path to file>);
logFile.getParentFile().mkdirs();
try (PrintWriter writer = new PrintWriter(logFile)) {
Iterator<Map.Entry<String, String>> iterator = etiquetteCache.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
try {
writer.print(entry.getKey() + ";" + entry.getValue() + "\r\n");
} catch (NullPointerException e) {
Cls_log.LogError(e);
}
}
writer.println();
} catch (IOException ex) {
Cls_log.LogError("Error writing etiquette log - " + ex.toString());
}
}

Categories