I have a text file with x amount of lines. each line holds a integer number. When the user clicks a button, an action is performed via actionlistener where it should list all the values as displayed on the text file. However, right now I have linenum set to 10 implying I already told the code that just work with 10 lines of the text file. So, if my text file has only 3 rows/lines of data...it will list those lines and for rest of the other 7 lines, it will spit out "null".
I recall there is a way to use ellipsis to let the program know that you don't know the exact value but at the end it calculates it based on the given information. Where my given information will the number of lines with numbers(data).
Below is part of the code.
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent event){
BufferedReader inputFile=null;
try {
FileReader freader =new FileReader("Data.txt");
inputFile = new BufferedReader(freader);
String MAP = "";
int linenum=10;
while(linenum > 0)
{
linenum=linenum-1;
MAP = inputFile.readLine();//read the next line until the specfic line is found
System.out.println(MAP);
}
} catch( Exception y ) { y.printStackTrace(); }
}}
just put instead of linenum > 0 the next line (MAP = inputFile.readLine()) != null
and delete the next lines, linenum=linenum-1;
MAP = inputFile.readLine(); and next time a bit of googling might help +)
The null value of the last line would not be printed because it sets the line to be the current line and compares it with the null value so if the last line is null it will not print it and what about the 10 lines limit? you can do it easily you can just add an an index to the for loop and to index and to check with && if the i is lower then 10
Test the value that comes back from BufferedReader.readLine(), if it is null stop looping, like so:
BufferedReader reader = new BufferedReader(new FileReader("Data.txt"));
try {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
} finally {
reader.close();
}
EDIT: forgot the requirement to take first 10 lines, you can change above code to put output in a list and return the list, then you can filter it through a function like this:
public List<String> takeFirst(int howMany, List<String> lines) {
return lines.size() <= howMany ? lines : lines.subList(0, howMany);
}
If the file is huge then this will be inefficient, of course, and if that matters you will end up doing something like:
BufferedReader reader = new BufferedReader(new FileReader("Data.txt"));
try {
int linesRead = 0;
for (String line; (line = reader.readLine()) != null && linesRead < 10;) {
System.out.println(line);
linesRead += 1;
}
} finally {
reader.close();
}
which is uglier but reads only the lines you need.
How about you don't print MAP if its value is null?
Related
So I have a text file with very simple text. Each line is simply make,model,vin#. I have about 3 or 4 lines to test. When I print out these lines, only the lines with even indexes get printed. If I don't include the else statement then it gives an out of bounds exception. So for example, with text file input as shown
Hi guys. I have a text file that is only a few lines long. On each line, it is formatted as such:make,model,number. When I run my program, it prints the lines normally until it gets to the third line of the text file(there's only 5 lines). This third line is where I get the index out of bounds exception.
public CarDealershipSystem(File carFile, File associateFile) {
try (BufferedReader br = new BufferedReader(new FileReader(carFile))) {
String line;
for(;;) {
line = br.readLine();
String[] lineArray = line.split(",");
System.out.println(lineArray[0]);
System.out.println(lineArray[1]);
System.out.println(lineArray[2]);
}
}catch(IOException e) {
e.getLocalizedMessage();
e.printStackTrace();
}
You have "line = br.readLine()" in two places in "while" cycle and in "if" block that causes two calls to readLine per cycle. Besides this block is pointless because the "while" condition already handles it.
tldr: remove
if((line = br.readLine()) == null) {
break;
}
you need a break when you reach the end of the file.
String line;
while((line = br.readLine()) != null) { //stop loop when line == null
line = br.readLine();
}
you need to check your input, before split
String[] lineArray = line.split(",");
if (lineArray != null && lineArray.length == 3) { //will help you avoid the ArrayIndexOutOfBoundsException exception
System.out.println(lineArray[0]);
System.out.println(lineArray[1]);
System.out.println(lineArray[2]);
}
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) {
}
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());
I am reading a log file line by line using BufferedReader. If a line is match an exact pattern i also acquire previous lines. This line number is entered by user. For example pattern is "ERROR" and line number 3 so i will store ERROR line and previous 3 lines.
FileInputStream fInStream = new FileInputStream(fileBase);
br = new BufferedReader(new InputStreamReader(fInStream));
while ((line = br.readLine()) != null) {
if(line.contains("ERROR")){
//here, i should write previous 3 lines and then ERROR line
bw.write(line + "\r\n");
}
}
Any suggestions will be appreciated.
You will have to keep the last n lines read saved so that you can always display them when encountering an error line.
The hard part is creating a data structure to keep track of the last n lines for you.
Perhaps you can use something like the answer to this question Looking for a circular fixed size array-based deque
So your code would look like this
Ring ring = new Ring(n);
while ((line = br.readLine()) != null) {
if(line.contains("ERROR")){
//note no checking to see if there are n lines
//currently stored in Ring maybe have to make a size() method
// and check that
for(int i=0; i<n; i++){
bw.write(ring.get(i) + "\r\n");
}
bw.write(line + "\r\n");
}
//add line to Ring here
ring.push(line);
}
As I said in my comment you can keep track of the last how-many-ever lines the user asked for at each step. So after reading a line of the log that does not contain "ERROR" you would add it to your list of remembered lines and if at that point that list of remembered lines is longer than the number of lines the user asked for, throw away the oldest entry in it.
So in code it would look something like this (you can just use a LinkedList for your data structure) :
// number of lines to print before the ERROR
int numContextLines = // user input
...
Deque<String> contextLines = new LinkedList<String>();
while ((line = br.readLine()) != null) {
if(line.contains("ERROR")){
// print out all of the context lines
for (String contextLine : contextLines) {
bw.write(contextLine + "\r\n");
}
bw.write(line + "\r\n");
} else {
// this is not an ERROR message so store it in our list of
// context lines that we can print when we find an ERROR
contextLines.addFirst(line);
// if this list has gotten too long then throw away the oldest entry in it
if (contextLines.size() > numContextLines) {
contextLines.removeLast();
}
}
}
I want to read strings from a file. When a certain string (><) is found, I want to start reading integers instead, and convert them to binary strings.
My program is reading the strings in and saving them in an ArrayList successfully, but
it does not recognise the >< symbol and therefore the reading of the binary strings is not successful.
The Code
try {
FileInputStream fstream = new FileInputStream(fc.getSelectedFile().getPath());
// Get the object of DataInputStream
DataInputStream ino = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(ino));
String ln;
String str, next;
int line, c =0;
while ((ln = br.readLine()) != null) {
character = ln;
System.out.println(character);
iname.add(ln); // arraylist that holds the strings
if (iname.get(c).equals("><")) {
break; // break and moves
// on with the following while loop to start reading binary strings instead.
}
c++;
}
String s = "";
// System.out.println("SEQUENCE of bytes");
while ((line = ino.read()) != -1) {
String temp = Integer.toString(line, 2);
arrayl.add(temp);
System.out.println("telise? oxii");
System.out.println(line);
}
ino.close();
} catch (Exception exc) { }
The file I'm trying to read is for example:
T
E
a
v
X
L
A
.
x
"><"
sequence of bytes.
Where the last part is saved as bytes and in the textfile appears like that. no worries this bit works. all the strings are saved in a new line.
< is two characters and iname.get(c) is only one character.
What u should do is test if ln equals > and then another test if the next character equals < . If both test pass then break out of the loop.
you will have to becarefull
Use a Scanner. It allows you to specify a delimiter, and has methods for reading input tokens as String or int.
Could you not do something like:
while ((ln = br.readLine()) != null){
character=ln;
System.out.println(character);
//
// Look for magic characters >< and stop reading if found
//
if (character.indexOf("><") >= 0) {
break;
}
iname.add(ln);
}
This would work if you didn't want to add the magic symbol to your ArrayList. Your code sample is incomplete - if you're still having trouble you'd need to post the whole class.