This question already has answers here:
Java if/else behaving strangely
(4 answers)
Closed 7 years ago.
I have this code:
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("hello.txt"));
String line;
while ((line = br.readLine().trim()) != null) {
if (line.startsWith("Hello")) {
line = br.readLine().trim();
} else {
... code ...
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
But once the file reaches the end, I get this error:
Exception in thread "main" java.lang.NullPointerException
On the line:
while ((line = br.readLine().trim()) != null) {
Why? How to fix it?
Try the following; ine which you are trying to read is null hence calling trim throws NPE;
while (br.readLine() != null)
{
line = br.readLine().trim()
}
while ((line = br.readLine().trim()) != null)
remove the trim()
and added it within the while loop.
line = line.trim();
When you try to read using readLine()
line = br.readLine().trim())
if br.readLine() return null, then calling trim() cause NPE.
while ((line = br.readLine()) != null) {
line.trim();
if (line.startsWith("Hello")) {
if ((line = br.readLine()) != null) {
line.trim();
}
} else {
}
}
Related
I have looked at two different ways of reading MultipartFile.
Using the forEach method works, but I can not break out of the forEach loop. I understand I can throw exceptions in the forEach loop to exit the loop but from what I have read it is not good practice.
private boolean validateFile(MultipartFile idFile) {
AtomicBoolean validated = new AtomicBoolean(true);
try {
InputStream inputStream = idFile.getInputStream();
new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines()
.forEach(
line -> {
line = line.trim();
if (line.length() != 3 || !line.matches("^[a-zA-Z0-9]*$")) {
validated.set(false);
}
}
);
} catch (Exception ex) {
validated.set(false);
}
return validated.get();
}
The problem with using forEach is that I can not break out of the loop after executing validated.set(false)
I have also tried using the method below in order to use breaks
private boolean validateFile(MultipartFile idFile) {
boolean validated = true;
InputStream inputStream = null;
BufferedReader br = null;
try {
inputStream = idFile.getInputStream();
br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.length() != 3 || !line.matches("^[a-zA-Z0-9]*$")) {
validated = false;
break;
}
}
} catch (Exception e) {
validated = false;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return validated;
}
The problem I am facing with the method above is that throw new RuntimeException(e); in the finally block causing sonar errors.
How can I read MultipartFile and being able to break out of the loop? I also don't want to use throws in the finally block since it causes sonar errors.
For your stream-based solution, you can use Stream.noneMatch(). On the first element, which matches the predicate it will stop evaluating the rest of the elements in the stream and return false.
private boolean validateFile(MultipartFile idFile) {
try {
InputStream inputStream = idFile.getInputStream();
return new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines()
.noneMatch(line -> line.length() != 3 || !line.matches("^[a-zA-Z0-9]*$"));
} catch (Exception ex) {
return false;
}
}
For the loop based solution, you can use try-with-resouces statement. It will automatically close the resources for you, so you don't need to do it manually.
private boolean validateFile(MultipartFile idFile) {
boolean validated = true;
try (InputStream inputStream = idFile.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.length() != 3 || !line.matches("^[a-zA-Z0-9]*$")) {
validated = false;
break;
}
}
} catch (IOException exc) {
return false;
}
return validated;
}
You could try to use .takeWhile in order to find the first not matching element. It will break the loop in the first occurrence of not matching element and returns the elements until that element.
I created a class in java to read a text file (.txt) and print on the screen the result on the screen. Script is reading the contents of the text file, but at the end it is displaying the message:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at com.desafioProgramacao.LerArquivo.main(LerArquivo.java:24)
I do not know why it displays the message. In the FINALLY class I tell it to close the FileReader and the BufferedReader if the contents of the file are null. Follow the Java code and screen prints.
public class LerArquivo {
private static final String NomeArquivo = "E:\\DesafioProgramacao\\matriculasSemDV.txt";
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(NomeArquivo);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
int num = Integer.parseInt(sCurrentLine);
System.out.println(num);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}}
The problem is the last line, it is a blank space. You can do:
while ((sCurrentLine = br.readLine()) != null) {
if (!sCurrentLine.isEmpty()) {
int num = Integer.parseInt(sCurrentLine);
System.out.println(num);
}
}
The cause on the surface is that your read an empty string and want to parse it to int
For the code,you need check the sCurrentLine value
while ((sCurrentLine = br.readLine()) != null) {
if(StringUtils.isNotBlank(sCurrentLine)){//StringUtils is from `commons-lang`
// or if(sCurrentLine.length()>0)
int num = Integer.parseInt(sCurrentLine);
System.out.println(num);
}
}
For the txt file,you need to remove all the empty line at the end of the file
Your file contains an empty line (probably at the end).
Replace your while loop with:
while ((sCurrentLine = br.readLine()) != null && !sCurrentLine.isEmpty())
The correct way to fix it is to catch that NumberFormatException and handle it properly, like that:
try {
int num = Integer.parseInt(sCurrentLine);
System.out.println(num);
} catch (NumberFormatException ex) {
System.out.println("Error reading line: " + sCurrentLine);
}
I have a comma delimited CSV file ans I have the code to read it from 2nd line. But it gives me the following error.
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space
This is my Code.
public static List<String> readCSV(String path){
BufferedReader br = null;
String[] cd = null;
String line ="";
String split=",";
List<String> list = new ArrayList<String>();
try {
br=new BufferedReader(new FileReader(path));
while ((line = br.readLine()) != null) {
boolean firstLine = true;
while (line != null && line.startsWith("child's Last Name")) {
if (firstLine) {
firstLine = false;
continue;
} else {
list.add(line);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}
How can I fix it with this code..
Thanks in Advance!
In your second while loop where are you assigning line again
while (line != null && line.startsWith("child's Last Name"))
Once this condition is satisfied, you are not reassigning it.
Your code should be different something like,
boolean firstLine = true;
while ((line = br.readLine()) != null)
{
if (firstLine)
{
firstLine = false;
continue;
}
else if(line != null && line.startsWith("child's Last Name"))
{
list.add(line);
}
}
try
br=new BufferedReader(new FileReader(path));
boolean firstLine = true;
while ((line = br.readLine()) != null) {
if (line.startsWith("child's Last Name")) {
if (firstLine) {
firstLine = false;
continue;
}
list.add(line);
}
}
There is no need for two while loops
Your problem has nothing to do with the 2nd line; You're simply trying to put the whole file in list and eventually, there's just too much to fit in memory. You have two choices:
Do not keep it all in memory! Process the line, do what you must, and don't store it, so it eventually gets garbage collected
If you really really must keep it all in memory, try increasing the amount of heap space available by starting java with a -Xmx parameter (run java -X for details)
UPDATE: oh oops, yes, as others said, you're also stuck in and endless loop. Consider this answer only once you've fixed that!
Usually, you get an out of memory error when you... well... run out of memory to run the application. Have you debugged into it? You could be stuck in an endless loop...
while (line != null && line.startsWith("child's Last Name")) {
Should this be an if statement?
EDIT:
while ((line = br.readLine()) != null) {
This really should be:
while(br.hasNext()) {
More info: Java - Read CSV with Scanner()
try this..
br=new BufferedReader(new FileReader(path));
br.readLine();
while ((line = br.readLine()) != null) {
if (line.startsWith("child's Last Name")) {
list.add(line);
}
}
This question already has answers here:
Quickly read the last line of a text file?
(10 answers)
Closed 9 years ago.
I am making a log and I want to read the last line of the log.txt file, but I'm having trouble getting the BufferedReader to stop once the last line is read.
Here's my code:
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Here's a good solution. In your code, you could just create an auxiliary variable called lastLine and constantly reinitialize it to the current line like so:
String lastLine = "";
while ((sCurrentLine = br.readLine()) != null)
{
System.out.println(sCurrentLine);
lastLine = sCurrentLine;
}
This snippet should work for you:
BufferedReader input = new BufferedReader(new FileReader(fileName));
String last, line;
while ((line = input.readLine()) != null) {
last = line;
}
//do something with last!
I am reading each line of the file in the below way
BufferedReader in = new BufferedReader(new FileReader(inFile));
while (null != (line = in.readLine())) {
}
I want to do some validation in the first line and last line alone. Is there any
way to check if it's a first line and last line inside the while loop
while (null != (line = in.readLine())) {
if(firstlineoffile) {
}
else if (lastlineoffile) {
}
else
{
}
}
Cool question. I played a bit round it and here's an SSCCE, just copy'n'paste'n'run it.
package com.stackoverflow.q2292917;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class Test {
public static void main(String... args) throws IOException {
// Create test file.
File file = new File("/test.txt");
PrintWriter writer = new PrintWriter(file);
writer.println("line 1");
writer.println("line 2");
writer.println("line 3");
writer.println("line 4");
writer.println("line 5");
writer.close();
// Read test file.
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String next, line = reader.readLine();
for (boolean first = true, last = (line == null); !last; first = false, line = next) {
last = ((next = reader.readLine()) == null);
if (first) {
System.out.println("first line: " + line);
} else if (last) {
System.out.println("last line: " + line);
} else {
System.out.println("normal line: " + line);
}
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
// Delete test file.
file.delete();
}
}
Output:
first line: line 1
normal line: line 2
normal line: line 3
normal line: line 4
last line: line 5
I however question the readability and interpretability by starters... ;)
String currentLine = in.readLine();
String nextLine = in.readLine();
boolean hasStarted = false;
while(null != currentLine){
if(!hasStarted){
//first line.
hasStarted = true;
}
//all your processing here.
if(null == nextLine){
//last line, cause there's nothing else coming up
}
currentLine = nextLine;
nextLine = in.readLine();
}
if you add a count, and rearrange your code a little, this should work (I haven't tested this so there may be syntax errros):
int count = 0;
String line = in.readLine();
while (line!=null) {
String currLine = line;
if(count==0){
//currLine is the first line
}
line = in.readLine();
if(line==null){
//currLine is the last line
}
if(count>0 && line!=null){
//do something with lines in between
System.out.println(currLine);
}
count++;
}
public class Vomitfirstline {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("Path"));
br.readLine();
{
while ((sCurrentLine = br.readLine()) != null)
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Someone might well come up with a more elegant solution than this, but here we go:
boolean isFirstLine = true;
do{
String line = in.readLine();
if(isFirstLine){
//this is the first line
isFirstLine = false;
}
else if(line==null){ //previous line was the last line
in.reset();
line = in.readLine();
//do last line specific stuff
break;
}
else {
//do stuff for lines in between
}
in.mark(100);
}while (line!=null);
I haven't tested this, so there might be minor errors. I haven't sorted out exception handling in this code. readLine(), mark() and reset() throw IOException and mark() can also throw IllegalArgumentException