Basically I've got an assignment which reads multiple lines from a .txt file.
There are 4 values in the text file per line and each value is separated by 2 spaces.
There are about 10 lines of data in the file.
After taking the input from the file the program then puts it onto a Database. The database connection functionality works fine.
My issue now is with reading from the file using a BufferedReader.
The issue is that if I uncomment any 1 of the 3 lines at the bottom the BufferedReader reads every other line. And if I don't use them then there's an exception as the next input is of type String.
I have contemplated using a Scanner with the .hasNextLine() method.
Any thoughts on what could be the problem and how to fix it?
Thanks.
File file = new File(FILE_INPUT_NAME);
FileReader fr = new FileReader(file);
BufferedReader readFile = new BufferedReader(fr);
String line = null;
while ((line = readFile.readLine()) != null) {
String[] split = line.split(" ", 4);
String id = split[0];
nameFromFile = split[1];
String year = split[2];
String mark = split[3];
idFromFile = Integer.parseInt(id);
yearOfStudyFromFile = Integer.parseInt(year);
markFromFile = Integer.parseInt(mark);
//line = readFile.readLine();
//readFile.readLine();
//System.out.println(readFile.readLine());
}
Edit: There was an error in the formatting of the .txt file. a missing value.
But now I get an ArrayOutOfBoundsException.
Edit edit: Another error in the .txt file! Turns out there was a single space instead of a double. It seems to be working now. But any advice on how to deal with file errors like this in the future?
The issue is that if I uncomment any 1 of the 3 lines at the bottom the BufferedReader reads every other line.
Correct. If you put any of those lines of code in, the line of text read will be thrown away and not processed. You're already reading in the while condition. You don't need another read. If you put any of those lines in, they will be thrown away and not proce
A compilable version of the code posted could be
public void read() throws IOException {
File file = new File(FILE_INPUT_NAME);
FileReader fr = new FileReader(file);
BufferedReader readFile = new BufferedReader(fr);
String line;
while ((line = readFile.readLine()) != null) {
String[] split = line.split(" ", 4);
if (split.length != 4) { // Not enough tokens (e.g., empty line) read
continue;
}
String id = split[0];
String nameFromFile = split[1];
String year = split[2];
String mark = split[3];
int idFromFile = Integer.parseInt(id);
int yearOfStudyFromFile = Integer.parseInt(year);
int markFromFile = Integer.parseInt(mark);
//line = readFile.readLine();
//readFile.readLine();
//System.out.println(readFile.readLine());
}
}
The above uses a single space (" " instead of the original " "). To split on any number of changes, a regular expression can be used, e.g. "\\s+". Of course, exactly 2 spaces can also be used, if that reflects the structure of the input data.
What the method should do with the extracted values (e.g., returning them in an object of some type, or saving them to a database directly), is up to the application using it.
Related
I am trying to read multiple lines from a file into an ArrayList as a String.
What I aim to do is to make it so the program reads from a file line by line until the reader sees a specific symbol (- in this case) and saves those rows as one single String. the code below makes every row a new string that it later adds to the list instead.
BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
String read;
while ((read = br.readLine()) != null) {
String[] splited = read.split("-");
carList.add(Arrays.toString(splited));
}
for (String carList2 : carList) {
System.out.println(carList2);
System.out.println("x");
}
First, you need to check if the read line contains "-".
If it doesn't, concatenate the line with the previous ones.
If it does, concatenate only the first part of the line with the previous line.
This is a quick implementation:
BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
String read;
String concatenatedLine = "";
while ((read = br.readLine()) != null) {
String[] splited = read.split("-");
// if line doesn't contains "-", splited[0] and read are equals
concatenatedLine += splited[0];
if (splited.length > 1) {
// if read line contains "-", there will be more than 1 element
carList.add(Arrays.toString(splited)); // add to the list
// store the second part of the line, in order to add it to the next ones
concatenatedLine = splited[1];
}
}
Note the output could not be what is expected if a line contains more than one -.
Also, concatenating String using + is not the best way to do it, but I let you find out more about that.
It's not very clear for me what is the output you desire.
If you would like to have each customer on one string without "-"
then you could try the following code:
while ((read = br.readLine()) != null) {
String splited = read.replace("-", " ");
carList.add(splited);
}
Please help me with adding number of lines of original file.
Im trying to write lines which met specified conditions from file A to file B. There is no problem, but I need to write number of lines of file A to the end of file B and also add number of lines of file B.
Program runs through file A, if condition is met, line is written to the file B, however I stuck to add number of lines after that.
For the last 2 hours I already tried second BufferedWriter, second "try" block, bw.write(lines) and many more, but nothing worked. System.out.println(lines) worked good, so Im really confused.
Here's my actual code:
try (
BufferedReader bReader = new BufferedReader(new FileReader("fileA.txt"));
BufferedWriter bWriter = new BufferedWriter(new FileWriter("fileB.txt"));
LineNumberReader lineNumberReader = new LineNumberReader(new FileReader("fileA.txt"));
){
lineNumberReader.skip(Long.MAX_VALUE);
int lines = lineNumberReader.getLineNumber();
lineNumberReader.close();
String line;
while ((line = bReader.readLine()) != null){
String[] values = line.split(" ");
int time = Integer.parseInt(values[3]);
if (time < 16){
bWriter.write(values[0] + ' ' + values[1] + ' ' + values[2] + "\n");
}
}
}
You can do that by adding bWriter.write(""+lines); after while loop.
You have to use bWriter.write(string) instead of bWriter.write(int).
bWriter.write(string) - the string value is written to the file as is.
bWriter.write(int); - It won't work because the int passed is converted to corresponding char and is then written to the file. The char corresponding to your lines value must be some non-printable character, and hence you are not able to see it.
I keep trying to check to see if two lines have the same content so I can keep it out of the file when it's all said and done. However, the if statement that checks to see if the two are similar isn't working properly. Even though the lines are seemingly similar, the if statement still sees it as false.
String fileLine = "";
String comp = "";
BufferedReader tempRead = new BufferedReader(new FileReader(new File("res/save.sav")));
PrintWriter tempWrite = new PrintWriter(new FileWriter(new File("res/tempSave.sav")));
for(String s: addToSave){
while((fileLine = tempRead.readLine()) != null){
comp = s.substring(0, s.length()-4);
System.out.print(fileLine.substring(0, comp.length()-1));
System.out.print(comp);
if(fileLine.substring(0, comp.length()-2).equals(comp)){
System.out.println("is gud");
}
}
}
tempWrite.close();
tempRead.close();
You will never have a string of one length, comp.length() - 2, be equal to another string of a different length, comp.length().
I need to process a big text file, there are almost 400 column in each line, and almost 800000 lines in the file, the format of each line in the file is like:
340,9,2,3........5,2,LA
what I want to do is, for each line, if the last column is LA, then print the first column of this line.
i write a simple program to do it
BufferedReader bufr = new BufferedReader(new FileReader ("A.txt"));
BufferedWriter bufw = new BufferedWriter(new FileWriter ("LA.txt"));
String line = null;
while ((line = bufr.readLine()) != null) {
String [] text = new String [388];
text = line.split(",");
if (text [387] == args[2]) {
bufw.write(text[0]);
bufw.newLine();
bufw.flush();
}
}
bufw.close();
bufr.close();
but it seems the length of an array cant be that big, i received a java.lang.ArrayIndexOutOfBoundsException
since i'm using split(",") in order to get the last column of a line, and it will be out of array bounds, how can I do with it? thanks.
text does not need to be initialized, String.split will create a correctly sized array:
String[] text = line.split(",");
You're also comparing Strings using reference equality (==). You should be using .equals():
if (text[387].equals(args[2])) { ... }
You're probably getting java.lang.ArrayIndexOutOfBoundsException because the the index 387 is too big. If you want to get last element, use this:
text[text.length - 1]
Modify and try this
String [] text = line.split(",");
if (text [text.length - 1].equals(args[2])) {
bufw.write(text[0]);
bufw.newLine();
bufw.flush();
}
Assuming args[2] is LA.
String [] text;
Change your code to this. You don't need to initialize a size. When the String.split method executes it will automatically initialize the correct size for your array.
If you just need the first and the last column, then there is no need to create an array out of the current line.
You could do something like this:
final String test = "340,9,2,354,63,5,5,45,634,5,5,2,LA";
final char delimiter = ',';
final String lastColumn = test.substring(test.lastIndexOf(delimiter) + 1);
if (lastColumn.equals("LA")) {
final String firstColumn = test.substring(0, test.indexOf(delimiter));
System.out.println(firstColumn);
}
This code extracts the last column first and tests it. If it matches "LA", then it extract the first column. It will ignore the remaining content of the line.
Your code would be:
BufferedReader bufr = new BufferedReader(new FileReader ("A.txt"));
BufferedWriter bufw = new BufferedWriter(new FileWriter ("LA.txt"));
String line = null;
while ((line = bufr.readLine()) != null) {
final String lastColumn = line.substring(line.lastIndexOf(delimiter) + 1);
if (lastColumn.equals(args[2])) {
bufw.write(line.substring(0, line.indexOf(delimiter)));
bufw.newLine();
bufw.flush();
}
}
bufw.close();
bufr.close();
(this code is not tested yet, but you get the idea :))
I have a text file that provides information for 22 golf courses, including name of course, name, location, designer, greens fee, par, year built, and total yards. As I read in, each line needs to be stored to the appropriate variable and then used to create a few objects. The first line of the file is the number of golf courses in the text file.
FileInputStream fstream = new FileInputStream(System.getProperty("user.dir")
+ "\\GolfCourses.txt");
//use file
DataInputStream in = new DataInputStream(fstream);
//read input
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Tree newTree = new Tree();
try{
String line = br.readLine();
if(line==null)
throw new IOException();
int clubs = Integer.parseInt(line);
for(int i = 0; i < clubs; i++){
String name = br.readLine();
String location = br.readLine();
double fee = Double.parseDouble(br.readLine());
int par = Integer.parseInt(br.readLine());
String designer = br.readLine();
int built = Integer.parseInt(br.readLine());
int yards = Integer.parseInt(br.readLine());
newTree.insert(new TreeNode(new GolfCourse(name, location, designer, fee, par, built, yards)));
}
in.close();
}catch(IOException e){
System.out.println(e);
}
The read-in seems to jump ahead of itself, so the program is trying to parse strings instead of numbers. I've never had this problem before so I'm lost on how to fix it.
EDIT: The code is now working as intended. The issue was coming from the "i <= clubs" piece of the for loop. Thank you for taking the time to help!
It's because your first br.readLine() would get your first line from the file, which is number of clubs. After the if statement, which fails, you are calling br.readLine(). This call would get the next line, as the first line was already retrived in the last call to br.realLine() in the if statement.
Try this:
String line = br.readLine();
if(line == null) {
throw new IOException();
}
int clubs = Integer.parseInt(line);
Read the file like this:
File f = new File("Path");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
Retriving of Fields:
If the fields like golf courses, name, locations are on a single line separated by "single space" for each entry:
- Use split(" ");
If the fields like golf courses, name, locations one per each line:
- Use split("\n"); Not "\\" but "\"
- Use for-loop with count of 8, so to get 8 fields.
Creation of Object:
- Create a Java bean with 8 fields, to hold these values.