NullPointerException when trying to read a file line by line (Java)? - java

I'm trying to read a file line by line, but every time I run my program I get a NullPointerException at the line spaceIndex = line.indexOf(" "); which obviously means that line is null. HOWEVER. I know for a fact that the file I'm using has exactly 7 lines (even if I print the value of numLines, I get the value 7. And yet I still get a nullpointerexception when I try to read a line into my string.
// File file = some File I take in after clicking a JButton
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(file.toPath(), charset)) {
String line = "";
int spaceIndex;
int numLines = 0;
while(reader.readLine()!=null) numLines++;
for(int i = 0; i<numLines; i++) {
line = reader.readLine();
spaceIndex = line.indexOf(" ");
System.out.println(spaceIndex);
}
PS: (I'm not actually using this code to print the index of the space, I replaced the code in my loop since there's a lot of it and it would make it longer to read)
If i'm going about reading the lines the wrong way, it would be great if someone could suggest another way, since so far every way I've tried gives me the same exception. Thanks.

By the time you start your for loop, the reader is already at the end of the file
(from the while loop).
Therefore, readLine() will always return null.
You should get rid of the for loop and do all of your work in the while loop as you first read the file.

You have two options.
First, you could read number of lines from a file this way:
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("File1")));
lnr.skip(Long.MAX_VALUE);
System.out.println(lnr.getLineNumber());
Then read the file right after:
while((line = reader.readLine())!=null)
{
spaceIndex = line.indexOf(" ");
System.out.println(spaceIndex);
}
This first option is an alternative (and in my my opinion, cooler) way of doing this.
Second option (and probably the more sensible) is to do it all at once in the while loop:
while((line = reader.readLine())!=null)
{
numLines++;
spaceIndex = line.indexOf(" ");
System.out.println(spaceIndex);
}

Related

How to read every second line from a file in java

Can someone tell me how to read every second line from a file in java?
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while(line != null){
//Do something ..
line = br.readLine()
}
br.close
One simple way would be to just maintain a counter of number of lines read:
int count = 0;
String line;
while ((line = br.readLine()) != null) {
if (count % 2 == 0) {
// do something with this line
}
++count;
}
But this still technically reads every line in the file, only choosing to process every other line. If you really only want to read every second line, then something like RandomAccessFile might be necessary.
You can do it in Java 8 fashion with very few lines :
static final int FIRST_LINE = 1;
Stream<String> lines = Files.lines(path);
String secondLine = lines.limit(2).skip(FIST_LINE).collect(Collectors.joining("\n"));
First you stream your file lines
You keep only the two first lines
Skip the first line
Note : In java 8, when using Files.lines(), you are supposed to close the stream afterwards or use it in a try-with-resource block.
This is similar to #Tim Biegeleisen's approach, but I thought I would show an alternative to get every other line using a boolean instead of a counter:
boolean skipOddLine = true;
String line;
while ((line = br.readLine()) != null) {
if (skipOddLine = !skipOddLine) {
//Use the String line here
}
}
This will toggle the boolean value every loop iteration, skipping every odd line. If you want to skip every even line instead you just need to change the initial condition to boolean skipOddLine = false;.
Note: This approach only works if you do not need to extend functionality to skip every 3rd line for example, where an approach like Tim's would be easier to modify. It also has the downside of being harder to read than the modulo approach.
This will help you to do it very well
You can use try with resource
You can use stream api java 8
You can use stream api supplier to use stream object again and again
I already hane added comment area to understand you
try (BufferedReader reader =
new BufferedReader(
new InputStreamReader(
new ByteArrayInputStream(x.getBytes()),
"UTF-8"))) { //this will help to you for various languages reading files
Supplier<Stream<String>> fileContentStream = reader::lines; // this will help you to use stream object again and again
if (FilenameUtils.getExtension(x.getOriginalFilename()).equals("txt")) { this will help you to various files extension filter
String secondLine = lines.limit(2).skip(FIST_LINE).collect(Collectors.joining("\n"));
String secondLine =
fileContentStream
.get()
.limit(2)
.skip(1)// you can skip any line with this action
.collect(Collectors.joining("\n"));
}
else if (FilenameUtils.getExtension(x.getOriginalFilename()).equals("pdf")) {
} catch (Exception ex) {
}

Ignore new lines while reading a file

I'm trying to read text inside a .txt document using console command java program < doc.txt. The program should look for words inside a file, and the file CAN contain empty new lines, so I've tried changing the while condition from:
while((s = in.nextLine()) != null)
to:
while((s = in.nextLine()) != "-1")
making it stop when it would have found -1 (I've also tried with .equals()), but it does not work. How can I tell my program to stop searching for words when there's no more text to examine? Otherwise it keeps stopping when it finds an empty string (newline alone or sequence of new lines).
I've only found solutions using BufferedReader, but I don't know how to use it in this situation where the file is being read by the console command java program < doc.txt.
I post the code inside the while, if it can be necessary:
while((s = in.nextLine()) != null) {
s = s.toLowerCase();
Scanner line = new Scanner(s);
a = line.next();
if(a.equals("word")) {
k++;
}
}
Proper way of figuring out when Scanner runs out of input is checking hasNextLine() condition. Use this loop to read a sequence of strings that includes empty lines:
Scanner in = new Scanner(System.in);
while(in.hasNextLine()) {
String s = in.nextLine();
System.out.println(s);
}
Demo.

Reading a file and performing functions based on the contents of the line

I'm wondering if it's possible to read a file by the line number, each with different values and make a condition where if that line contains a certain string or number specified. If it did it would, for example, take the content specified in that line into a variable?
So in a file line one has Age: 50, line 2 has Age: 23, line 3 has Age: 34. What I'm hoping for is that I look specifically at line 3 and take the number 34 and place it in a variable for use in my program.
If it is possible, how would you go about doing this?
I would say, it is not possible to directly address a specific line unless - perhaps you know the line sizes of your file, etc... to seek through the file. But you can use this to go through your file, line by line:
String line;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
// do some cool stuff with this line.
}
br.close();
Possible duplicate: Reading a file and performing functions based on the contents of the line
You can always iterate through each line, keeping track of the line via an int or a short.
some code:
String line;
BufferedReader br = new BufferedReader(new FileReader(FILE_HERE));
int line = 0;
while ((line = br.readLine()) != null) {
line++;
if(line == 3){
//do whatever you want
}
}
br.close();
I will add that getting something from one single line while others also have identical info is bad
you can use the scanner object to read through a file. you would use the delimiter to find the info you want and a counter to keep track of the line, then put it in an arraylist or something. depending on what you want to do.
Scanner in = new Scanner(filename);
int line = 0;
in.useDelimiter("[regex of the info you are looking for]");
while in.hasNext()) {
line++
//do something
}

Efficiently parsing and writing to a file in Java

I have a file that has no new line characters. I want a new line character every 160 characters.
To do this, I read the file, and then do:
String newLine = "";
int lineSize = 160;
char[] line = new char[lineSize];
while (rEntrada.read(line) > 0) {
newLine = new String(line);
String parsedLine = parseLine(newLine, date);
fw.write(parsedLine);
}
where parseLine takes care of some extra parsing of the line. My main question is if doing a "new String" inside a while loop is inefficient or not recommended or if you guys see anything that could be done better in this code. I'm really trying to get better at coding!
Thanks!
Try this.
First read the single line.
FileReader r = new FileReader(new File("<file-name>"));
// A buffered reader is fast
BufferedReader = reader = new BufferedReader(r);
String line = reader.readLine();
// Also use try-catch blocks!
Now iterate over the string and insert a \n at every 160th position.
StringBuilder sb = new StringBuilder();
int counter = 0;
for (int i=0; i<line.length(); i++){
sb.append(line.charAt(i));
counter++;
if (counter==160){
sb.append("\n");
counter = 0;
}
}
line = sb.toString();
Now you could write this line to the file.
It looks good to me, the only inefficiency I can see is if parseLine could be written better, possibly being passed line instead of newLine. It depends on what parseLine actually does.
Take a look at StringBuffer and see if it isn't usable in this case.
StringBuffer API Documentation
StringBuilder may also be of interest if you're not multi-threaded.

java nested while loop using readline

I'm confused. I'm trying to loop though 2 files looking at the first token in every line of the first file and comparing it to the third token of every line of the second file. Here is the logical structure in the form of a nested while loop:
BufferedReader reader1 = new BufferedReader(new InputStreamReader(new FileInputStream(fromFile1)));
BufferedReader reader2 = new BufferedReader(new InputStreamReader(new FileInputStream(fromFile2),"EUC-JP"));
String line1, line2 = null;
String temp1, temp2 = null;
while ((line1=reader1.readLine()) != null)
{
StringTokenizer st1 = new StringTokenizer(line1);
temp1 = "U"+st1.nextToken();
while((line2=reader2.readLine()) != null)
{
StringTokenizer st2 = new StringTokenizer(line2);
temp2 = st2.nextToken();
temp2 = st2.nextToken();
temp2 = st2.nextToken();
if(temp2.equals(temp1));
{
System.out.println(temp1+" "+temp2);
}
}
}
However, all I see in the output is the first token from the first line of the first file and the third token from every line of the second file repeated 6,000 (the length of file 2) times regardless of whether they were "equal" or not. Does this have to do with their different encodings? I can see that having an effect on the equals test, but why isn't the loop behaving properly?
Cheers,
Brandon
it's the ; behind the if
if(temp2.equals(temp1));
But it wouldn't probably work anyway as expected, since you must reopen file 2 within the outer loop, otherwise it will only work correctly for the first line of file 1

Categories

Resources