I got Null pointer exception when reading data from file.if its returning a junk value how to handle that. if i didn't give trim giving some junk value.
My code is:
BufferedReader br = null;
try {
String sCurrentval = "";
br = new BufferedReader(new FileReader("filepath"));
while ((sCurrentval = br.readLine()) != null) {
System.out.println("Reading from File "+sCurrentval);
}
if(sCurrentval != null){
sCurrentval = sCurrentval.trim();
}
System.out.println("outside : Reading from File "+sCurrentval);
if(sCurrentval != null && !sCurrentval.equalsIgnorecase("")){
try{
val = Integer.parseInt(sCurrentval.trim());
}catch(Exception e){
e.printStackTrace();
}
}else{
System.out.println("Reading Value null ");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Your BufferedReader br = null; with in the try. But your finally also using the same variable br.
try
{
//
BufferedReader br = null; // declared with in try
//
}
finally {
try {
if (br != null) // In this line the br is not identified
br.close();
} catch (IOException ex)
{
ex.printStackTrace();
}
Try to declare the BufferReader outside the try
BufferedReader br = null;
And then your while loop is only for the printing the value of the variable. Include the below if else condition within the while and then try the below code.
while ((sCurrentval = br.readLine()) != null)
{
System.out.println("Reading from File " + sCurrentval);
if (sCurrentval != null && !sCurrentval.trim().isEmpty())
{
try
{
val = Integer.parseInt(sCurrentval.trim());
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
System.out.println("Reading Value null ");
}
}
Related
I'm new to using the Checkmarx tool and just checking for security flaws in code in general. I have a method which is supposed to read from an input stream. The method works, however I am getting XXE and SSRF errors.
public static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(Normalizer.normalize(line, Normalizer.Form.NFD));
}
} catch (IOException e) {
LOG.error(
"********************",
e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
LOG.error(
******************,
e);
}
}
}
return sb.toString();
}
In my program I want to read a file and then analyze it. To do this I made this simple code :
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader("E:\\Users\\myFile.txt");
br = new BufferedReader(fr);
[...]
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Unfortunately when my file doesn't exist I have a java.io.FileNotFoundException exception that is thrown. But when I read the doc of java.io.FileNotFoundException I can see that java.io.IOExceptionis a superclass of java.io.FileNotFoundException.
So, why does java.io.FileNotFoundException is not caught by catch (IOException ex)?
Also i know that I must do catch (FileNotFoundExceptionex) but I don't understand why I have this error.
It does:
public void test() {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader("E:\\Users\\myFile.txt");
br = new BufferedReader(fr);
System.out.println("OK");
} catch (IOException e) {
System.out.println("Caught in try.");
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
System.out.println("Caught in catch.");
ex.printStackTrace();
}
}
}
prints
Caught in try.
java.io.FileNotFoundException: E:\Users\myFile.txt (The system cannot find the path specified) ...
BTW: You can use try with resources for a much more effective and tidy solution.
public void test() {
try (BufferedReader br = new BufferedReader(new FileReader("E:\\Users\\myFile.txt"))){
System.out.println("OK");
} catch (IOException e) {
System.out.println("Caught in try.");
e.printStackTrace();
}
}
In my app I am displaying the first portion of each line of the CSV in a JList, and when it is selected and a button is pressed (delete) I want it to remove that line from the file based on the first entry. I am trying the method where you have a temp file then write to it then rename it at the end but that isnt working out for some reason. Any ideas?
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Delete service
String selected = (String) jList1.getSelectedValue();
File passwords = new File("/users/aak7133/desktop/passwords.txt");
File temp = new File("/users/aak7133/desktop/temp.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(passwords));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String line;
System.out.println(selected);
while ((line = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
//String trimmedLine = line.trim();
if (line.contains(selected)) {
continue;
}
writer.write(line);
}
boolean successful = temp.renameTo(passwords);
} catch (Exception e) {
}
updateList();
clearFields();
}
The problem is actually caused by the open reader and writer. This should work:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
String selected = (String) jList1.getSelectedValue();
BufferedReader reader = null;
BufferedWriter writer = null;
try {
File passwords = new File("/users/aak7133/desktop/passwords.txt");
File temp = File.createTempFile("temp", ".txt", new File("/users/aak7133/desktop/"));
reader = new BufferedReader(new FileReader(passwords));
writer = new BufferedWriter(new FileWriter(temp));
String line;
System.out.println(selected);
while ((line = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
// String trimmedLine = line.trim();
if (line.contains(selected)) {
continue;
}
writer.write(line + "\n");
}
if (passwords.canWrite()) {
try {
reader.close();
reader = null;
} catch (IOException ignore) {}
try {
writer.close();
writer = null;
} catch (IOException ignore) {}
String path = passwords.getAbsolutePath();
passwords.delete();
boolean successful = temp.renameTo(new File(path));
System.out.println(successful);
}
} catch (Exception e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {}
}
if (writer != null) {
try {
writer.close();
} catch (IOException ignore) {}
}
}
updateList();
clearFields();
}
I figured out I needed to put passwords.delete() before temp.renameTo(passwords). This fixed the issue right away.
is any way to change this java code (read from com port) to read lines ?
eg.
I'm using rxtx com
original method:
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[10];
int numBytes = 0;
try {
while (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);
}
} catch (IOException e) {
System.out.println(e);
}
System.out.println(Arrays.toString(readBuffer));
}
}
Assuming inputStream is an InputStream, you could wrap it with an InputStreamReader and wrap that with a BufferedReader (that has a readLine()). Something like,
case SerialPortEvent.DATA_AVAILABLE:
String line;
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
or you could possible use with try-with-resouces,
case SerialPortEvent.DATA_AVAILABLE:
String line;
BufferedReader br = null;
try (br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));) {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
I am finding some difficulties to do the following operation in Java:
I have to take the content of an xml file and print it
I do something like this:
System.out.println("settings.xml: " + ClassLoader.getSystemResourceAsStream("/home/andrea/Documenti/dir1/dir2/dir3/dir4/dir5/dir6/dir7/dir8/src/settings.xml"));
The problem is that the result of this statment is:
settings.xml: null
Why? What can I do to do it?
Tnx
Andrea
You can use this function:
private String getStringFromFile(File file)
{
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((line = br.readLine()) != null)
{
sb.append(line);
}
} catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return sb.toString();
}
For example:
System.out.println("settings.xml: " + ClassLoader.getSystemResourceAsStream("home/andrea/Documenti/dir1/dir2/dir3/dir4/dir5/dir6/dir7/dir8/src/settings.xml"));