BufferedReader.readline() returns null - java

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

Related

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

Close this "FileInputStream" sonar

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.

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 ?

wait for method of process class doesn't return

I have Process Class in my code and that couldn't read the inputbufferreader data when i try to reading the larger number of data from inputbuffer and waitfor method of process class never return anything
this issue is happened in live server
but below code running fine and read the all the data from inputbuffer in local server
private static JSONObject ExecJniApp(String inputJsonString) throws JniException
{
int exitStatus = 0;
String workingDirectory = JniSettings.getJniAppDirectory();
String command = workingDirectory + binaryName;
System.out.println("ExecJniApp: inputJsonString: " + inputJsonString);
String outputString = "";
try
{
Process p = Runtime.getRuntime().exec(command, null, new File(workingDirectory));
// send input vi stdin
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writer.write("\n>>>>>>>>>>");
writer.write(inputJsonString);
writer.write("<<<<<<<<<<\n");
writer.flush();
if (JniSettings.isLinux())
{
p.waitFor();
}
else
{
// System.out.println("ExecJniApp: windows wait for");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
for (;;)
{
String line = reader.readLine();
if (line == null)
{
break;
}
// System.out.println(line);
outputString += line + "\n";
}
// exit code of command and log error detail
// exit status = 0 -> Success
exitStatus = p.exitValue();
if (exitStatus != 0)
{
System.out.println("ExecJniApp: inputJsonString: " + inputJsonString);
System.out.println("ExecJniApp: outputString:\n" + outputString);
throw new Exception("Exit status other than zero :- " + exitStatus + "\noutput: ");
}
}
catch (Exception e)
{
// System.out.println("ExecJniApp failed");
e.printStackTrace();
throw new JniException("JniInterface failed");
}
System.out.println("ExecJniApp: outputString:\n" + outputString);
int index1 = outputString.indexOf(">>>>>>>>>>");
if (index1 == -1)
{
// System.out.println("ExecJniApp failed, Invalid output format");
throw new JniException("ExecJniApp failed, Invalid output format");
}
index1 += 10;
int index2 = outputString.indexOf("<<<<<<<<<<");
if (index2 == -1 || index2 <= index1)
{
// System.out.println("ExecJniApp failed, Invalid output format");
throw new JniException("ExecJniApp failed, Invalid output format");
}
String outputJsonString = outputString.substring(index1, index2);
// System.out.println("ExecJniApp: outputJsonString: " + outputJsonString);
JSONParser parser = new JSONParser();
JSONObject obj = null;
try
{
obj = (JSONObject) parser.parse(outputJsonString);
}
catch (ParseException e)
{
// System.out.println("ExecJniApp failed, Json parse failed");
e.printStackTrace();
throw new JniException("JniInterface failed, Json parse failed");
}
Object errorObject = obj.get("error");
if (errorObject != null)
{
String errorString = errorObject.toString();
// System.out.println("ExecJniApp failed, " + errorString);
throw new JniException("ExecJniApp failed, " + errorString);
}
return obj;
}
Just replace your code with below code.
Must close your InputStream connection.
Process p = Runtime.getRuntime().exec(command, null, new File(workingDirectory));
// send input vi stdin
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writer.write("\n>>>>>>>>>>");
writer.write(inputJsonString);
writer.write("<<<<<<<<<<\n");
writer.flush();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
for (;;)
{
String line = reader.readLine();
if (line == null)
{
break;
}
// System.out.println(line);
outputString += line + "\n";
}
p.getOutputStream().close();
p.getInputStream().close();
}
catch(Exception e)
{
e.printStackTrace();
}
if (JniSettings.isLinux())
{
p.waitFor();
}
else
{
// System.out.println("ExecJniApp: windows wait for");
}
// exit code of command and log error detail
// exit status = 0 -> Success
exitStatus = p.exitValue();
if (exitStatus != 0)
{
System.out.println("ExecJniApp: inputJsonString: " + inputJsonString);
System.out.println("ExecJniApp: outputString:\n" + outputString);
throw new Exception("Exit status other than zero :- " + exitStatus + "\noutput: ");
}

Categories