java nested while loop using readline - java

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

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) {
}

Java BufferedReader to String Array

I was looking through a lot of diffrent subjects here on stackoverflow but couldn't find anything helpful so far :/
So this is my problem. I am writing a filecopier. The problem occurs already at reading the file. My test docoument got 3 lines of random text. All those 3 lines should get written in a string array. The problem is that only the 2nd line of the textdocument gets written in the array and I can't figure out why. Already debugged it, but didn't get me any further.
I know there are diffrent solutions for a filecopier with diffrent classes etc. But I would really like to get it running with the classes I used here.
String[] array = new String[5];
String datei = "test.txt";
public String[] readfile() throws FileNotFoundException {
FileReader fr = new FileReader(datei);
BufferedReader bf = new BufferedReader(fr);
try {
int i=0;
//String Zeile = bf.readLine();
while(bf.readLine() != null){
array[i] = bf.readLine();
// System.out.println(array[i]); This line is for testing
i++;
}
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
return array;
You're calling readLine() twice for each iteration of the loop, thereby discarding every other line. You need to capture the value returned by every call to readLine(), because each readLine() call advances the reader's position in the file.
Here's the idiomatic solution:
String line;
while((line = bf.readLine()) != null){
array[i] = line;
i++;
}
Here you read 2 lines:
while(bf.readLine() != null){
array[i] = bf.readLine();
// System.out.println(array[i]); This line is for testing
i++;
}
You have to change your Code to:
String line = null;
while((line =bf.readLine()) != null){
array[i] = line;
// System.out.println(array[i]); This line is for testing
i++;
}
The problem is here :
while(bf.readLine() != null)
readLine() reads a line and returns the same at the same time it moves to the next line.
So instead of just checking if the returned value was null also store it.
String txt = null;
while((txt = bf.readLine()) != null)
array[i++] = txt;
I think its because you are calling readLine() twice. First time in the loop, and then second time when you put it in the array. So, it reads a line at the beginning of the loop (line 1), then first line of code inside the loop (line 2 that you see)
I am use Stream.
Not a. This form only applies to reading text files.
BufferedReader bf = new BufferedReader(fr);
// ...
List<String> lines = bf.lines().collect(Collectors.toList());

write multiple string line in a file

I want to write a file in multiple line in a file. for example:
first line: a b c d e f g h i
second line: j k l m n o p q r
third line: s t u v w x y z 1
but the code I made cannot do so. it only prints on one line every time I try to write in it. Here's my code:
FileOutputStream write = new FileOutputStream ("file.txt");
PrintStream print = new PrintStream (write);
BufferedReader in = new BufferedReader(new FileReader(data));
String read;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\n");
for (int z = 0; z<splited.length; z++){
print.print(splited[z]+" ");
}
}
print.println();
how can i fix this?
You need to move print.println() inside the while loop.
The correct way is as follows :
while ((read = in.readLine()) != null) {
String[] splited = read.split("\n");
for (int z = 0; z<splited.length; z++){
print.print(splited[z]+" ");
}
print.println(); // correct place for println
}
So first of all, readLine reads one line, up to a newline, so there is no need to call split("\n") because it will always return the string itself.
Second, you never write a newline to the output file, so it ends up having all the lines unrolled in one. You can just modify the line print.print(splited[z] + " "); to print.print(splited[z] + "\n");.
I have altered your code in a few ways to improve readability and performance.
I am now using a BufferedWriter instead of a PrintStream, which has a nice method for writing newlines.
I am using try-with-resources. This is a Java 7+ feature that automatically closes connections, streams, and buffers for you. In your current code I don't see you closing either the reader or the writer. For such a small program this is not a big deal, but it is good practice to close them.
I used a for loop instead of a while loop. This is a nice trick I picked up that saves me from defining read in a higher scope than I need it (scope-creep).
-
try (BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
BufferedReader reader = new BufferedReader(new FileReader(data)))
{
for (String read = reader.readLine(); read != null; read = reader.readLine()) {
writer.append(read);
writer.newLine();
}
}

NullPointerException when trying to read a file line by line (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);
}

Reading certain lines only from input?

If i have some code such as input = new BufferedReader(new FileReader(args[0])); And the input file contain pairs of lines, how can I make it so only the first line from each line is imported? So in other words, every odd numbered line only?
Thanks
You might like to consider the use of java.io.LineNumberReader to make the filtering of odd lines (lineNo % 2 == 1) simpler. Or in an alternative approach, if you are using JDK7, you could use the java.nio.files.Files.readAllLines() method and again filter the odd ones upon iteration.
String line = input.readLine();
while (line != null) {
// do something with the line
// Skip every other line
input.readLine();
// Get next line
line = input.readLine();
}
something like this will read in the file and give you every 2nd line in a string buffer.
BufferedReader br = new BufferedReader(new FileReader(args[0]));
String line;
StringBuffer endResult = new StringBuffer(1000);
int lineNumber=1;
while ((line=br.readLine()) != null) {
//every odd line will be added, 1, 3, 5 etc
if (lineNumber++%2==1) {
endResult.append(line+"\n");
}
}

Categories

Resources