This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
So i want to read a String and an int from a text file and it gets me java.lang.ArrayIndexOutOfBoundsException: 1
public class GetNameAndNumber{
private ArrayList <NameAndNumber> list = new ArrayList <NameAndNumber>();
BufferedReader buf = new BufferedReader(new FileReader("NameAndNumber.txt"));
String linie = buf.readLine();
while(true)
{
linie = buf.readLine();
if(linie == null)
break;
else
{
String split[] = linie.split(" ");
NameAndNumber nan = new NameAndNumber(split[0], Integer.parseInt(split[1]));
list.add(nan);
}
}
}
the "NameAndNumber" class has a String and an int
and this is the text file:
John 1
David 0
Ringo 55
What i don't know is why this one gives me an error, but when i read 2 strings and then an int like
NameAndNumber nan = new NameAndNumber(split[0], split[1], Integer.parseInt(split[2])); - this "NameAndNumber" having two strings and an int
for a text file like
Johnny John 8
Mathew John 0
it gives me no errors and stores the values correctly. why ?
You most likely have a line without 2 strings on it. Maybe a blank line at the end of the file. I would suggest adding code to display each line right after you read it in, for debugging purposes. Then you can see where the bad line is in your input file.
linie = buf.readLine();
System.out.println("line: '" + linie + "'");
You could add additional code to skip lines that don't have two strings.
String split[] = linie.split(" ");
if (split.length < 2) continue; // skip bad input
I am assuming in you first file you have some empty spaces, because I ran your code and it worked fine. I made it fail by adding some empty spaces at the end with the Index out of exception.
One thing you can do it add some checks as follows by doing a trim and checking if the line is empty.
linie = buf.readLine().trim();
if(linie == null || linie.isEmpty())
break;
Try this
for(;;) {
String line = bufferedReader.readLine();
if (line == null) {
break;
}
}
Related
This question already has answers here:
Getting java.lang.NumberFormatException in the code
(3 answers)
Closed 2 years ago.
I'm reading in from a file that contains an item name and its quantity. I'm getting a NumberFormatExpression when I try to convert the quantity amount to an int. I feel it may be due to the - sign, but even after removing the - it stills throws the exception
String line = reader.readLine();
while (line != null) {
String[] delimiter = line.split(",");
int originalQuantity = Integer.parseInt(delimiter[1]);
line = reader.readLine();
}
the file contents:
Toilet Papers, -10
Hand sanitizers, 12
You're including a space at the beginning of the number. Use the trim method to get rid of it.
String line = reader.readLine();
while (line != null) {
String[] delimiter = line.split(",");
int originalQuantity = Integer.parseInt(delimiter[1].trim()); // <-- trim here
line = reader.readLine();
}
This question already has answers here:
How can I read comma separated values from a text file in Java?
(6 answers)
How do I split a string in Java?
(39 answers)
Closed 3 years ago.
I want to load data from a text file as required for part of a basic project. E.g. a text file can look like this:
201,double,70.00,2,own bathroom
202,single,50.00,2,own bathroom
Each piece of data is seperated by a comma, and in this case goes in the order: room number, room type, cost, amount of people, with/without bathroom and there's 5 data for each room and each room information is on a new line.
The code below reads each line individually, but how do I get it to read and store each data/word from the line (without the comma obviously)?
try{
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = reader.readLine();
while (line != null){
System.out.println(line);
line = reader.readLine();
}
reader.close();
} catch(IOException ex){
System.out.println(ex.getMessage());
}
I saw an example using scanner but I heard that it's slower and less efficient.
I also tried using split but I can't figure out how to do it properly.
Thanks.
You can use Files.readAllLines() method and map the data to the dedicated object. Assuming you have such Room object with appropriate constructor you can read and store data like:
List<String> strings = Files.readAllLines(Paths.get("test.txt"));
List<Room> rooms = new ArrayList<>();
for (String line : strings) {
String[] split = line.split(",");
Integer roomNumber = Integer.valueOf(split[0]);
String roomType = split[1];
Double roomCost = Double.valueOf(split[2]);
Integer amount = Integer.valueOf(split[3]);
String bathroom = split[4];
Room r = new Room(roomNumber, roomType, roomCost, amount, bathroom);
rooms.add(r);
}
Then you can get the information for some room for example by room number:
Room room = rooms.stream()
.filter(r -> r.getRoomNumber() == 102)
.findFirst().orElseThrow(NoSuchElementException::new);
Note: If you are using java10 or above you can use orElseThrow() without parameters
You can split the line by the comma , and get an array of values:
try{
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = reader.readLine();
String data[] = null;
while (line != null){
System.out.println(line);
line = reader.readLine();
data = line.split(","); //data will have the values as an array
}
reader.close();
} catch(IOException ex){
System.out.println(ex.getMessage());
}
If I´m not wrong then the described format is the csv format ( https://en.wikipedia.org/wiki/Comma-separated_values)
Here is good overview how you can read csv data:
https://www.baeldung.com/java-csv-file-array
This question already has answers here:
Parse and read data from a text file [duplicate]
(3 answers)
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Effective way to read file and parse each line
(3 answers)
parsing each line in text file java
(7 answers)
Closed 5 years ago.
I got .txt file with nationalities and phone numbers in different formats and all these in single quote symbols, also it contains empty lines (''):
''
'French'
'1-500'
'0345134123'
''
''
'German'
etc
after I parse with the help of readLine() I got arr[0] with each of these lines.
I need to put lines into different arrays: lines with 'nationality' into one array and lines with 'phone numbers' into other.
I tried this
if(!arr[0].equals("''")){
String[] arr1 = arr[0].split("'");
if(!arr1[1].matches("[0-9]+)"){
nations[n] = arr1[1];
n++;
}
else {
phone_numbers[p] = arr1[1];
p++;
}
}
Ofcourse it didn't work
In your question you said that you want
to put lines into different arrays: lines with 'nationality' into one array and lines with 'phone numbers' into other.
public static void main(String[] args) {
try{
File file = new File("path\\to\\yourfile");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
String nationalities = "";
String phones = "";
while((line = br.readLine()) != null){
String[] s = line.split("'");
if(s.length > 0){
if(s[1].matches("[a-zA-Z]+")){
// nationalities
nationalities += (nationalities.isEmpty()) ? s[1] : " " + s[1];
}else{
// line with phone numbers
phones += (phones.isEmpty()) ? s[1] : " " + s[1];
}
}
}
String[] nationArr = nationalities.split(" ");
String[] phoneArr = phones.split(" ");
for(String val : nationArr){
System.out.println(val);
}
System.out.println("------------");
for(String val : phoneArr){
System.out.println(val);
}
}catch(IOException e){
System.out.println("Error");
}
}
I tested with this text file
''
'French'
'1-500'
'0345134123'
''
''
'Japan'
'2-200'
'08078933444'
''
''
''
'Germany'
'2-300'
'00078933444'
''
You will get two array, nationality[nationArr] and line with phone[phoneArr].
Here is the answer.
French
Japan
Germany
------------
1-500
0345134123
2-200
08078933444
2-300
00078933444
I would suggest implementing some sort of system to differentiate between the types of lines. You could put 'n' at the start of the line for nationality, then detect it in your code.... Or if you knew the exact order of these lines e.g. nationality,number,nationality,number... you could easily separate these lines e.g. lineNumber%numOfLineTypes==0 would give you the first type of line...
i have a question. I have a text file with some names and numbers arranged like this :
Cheese;10;12
Borat;99;55
I want to read the chars and integers from the file until the ";" symbol, println them, then continue, read the next one, println etc. Like this :
Cheese -> println , 10-> println, 99 -> println , and on to the next line and continue.
I tried using :
BufferedReader flux_in = new BufferedReader (
new InputStreamReader (
new FileInputStream ("D:\\test.txt")));
while ((line = flux_in.readLine())!=null &&
line.contains(terminator)==true)
{
text = line;
System.out.println(String.valueOf(text));
}
But it reads the entire line, doesn`t stop at the ";" symbol. Setting the 'contains' condition to false does not read the line at all.
EDIT : Partially solved, i managed to write this code :
StringBuilder sb = new StringBuilder();
// while ((line = flux_in.readLine())!=null)
int c;
String terminator_char = ";";
while((c = flux_in.read()) != -1) {
{
char character = (char) c;
if (String.valueOf(character).contains(terminator_char)==false)
{
// System.out.println(String.valueOf(character) + " : Char");
sb.append(character);
}
else
{
continue;
}
}
}
System.out.println(String.valueOf(sb) );
Which returns a new string formed out of the characters from the read one, but without the ";". Still need a way to make it stop on the first ";", println the string and continue.
This simple code does the trick, thanks to Stefan Vasilica for the ideea :
Scanner scan = new Scanner(new File("D:\\testfile.txt"));
// Printing the delimiter used
scan.useDelimiter(";");
System.out.println("Delimiter:" + scan.delimiter());
// Printing the tokenized Strings
while (scan.hasNext()) {
System.out.println(scan.next());
}
// closing the scanner stream
scan.close();
Read the characters from file 1 by 1
Delete the 'contains' condition
Use a stringBuilder() to build yourself the strings 1 by 1
Each stringBuilder stops when facing a ';' (say you use an if clause)
I didn't test it because I'm on my phone. Hope this helps
This question already has answers here:
Java: Reading a file into an array
(5 answers)
Closed 1 year ago.
I'll try to be as clear as possible but pardon me if my question is not perfect.
I have a txt file with several lines of data. example:
123 ralph bose 20000 200 1 2
256 ed shane 30000 100 2 4
...
I need to read each line sequentially and pass it back to a method in a separate class for processing. I know how to break down each line into elements by using StringTokenizer.
However, i'm not sure how to read one line at a time, pass back the elements to the other class and then, once the processing is done, to read the NEXT line. Method cooperation between my classes works fine (tested) but how do i read one line at a time?
I was thinking of creating an array where each line would be an array element but as the number of lines will be unknown i cannot create an array as i don't know its final length.
Thanks
Baba
EDIT
rough setup :
Class A
end_of_file = f1.readRecord(emp);
if(!end_of_file)
{
slip.printPay(slipWrite);
}
Class B
public boolean readRecord(Employee pers) throws IOException {
boolean eof = false ;
String line = in.readLine() ;
???
}
filename is never passed around
so up until here i can read the first line but i think i need a way to loop through the lines to read them one by one with back and forth between classes.
tricky...
There are lots of ways to read an entire line at a time; Scanner is probably easiest:
final Scanner s = new Scanner(yourFile);
while(s.hasNextLine()) {
final String line = s.nextLine();
YourClass.processLine(line);
}
void readLine(String fileName)
{
java.io.BufferedReader br = null;
try
{
br = new java.io.BufferedReader(new java.io.FileReader(fileName));
String line = null;
while(true)
{
line = br.readLine();
if(line == null)
break;
// process your line here
}
}catch(Exception e){
}finally{
if(br != null)
{
try{br.close();}catch(Exception e){}
}
}
}
Also if you want to split strings... use
String classes split method. for splitting depending on space... you can do ... line.split("\\s*")
Hope it works