This question already has answers here:
ArrayIndexOutOfBoundsException for String.split()
(2 answers)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I got ArrayIndexOutOfBoundsException: 1 at this line String name = pieces[1]; in the following function:
public static void loadFile() throws FileNotFoundException, IOException {
file = new File("C:\\Users\\DELL\\OneDrive - Philadelphia University\\Desktop\\NetBeansProjects\\CaloriesIntakeApp\\src\\main\\webapp\\WEB-INF\\data\\data.txt");
try (BufferedReader inputStream = new BufferedReader(new FileReader(file))) {
String line;
while ((line = inputStream.readLine()) != null) {
String[] pieces = line.split(" ");
String id = pieces[0];
String name = pieces[1];
int grms = Integer.parseInt(pieces[2]);
int calories = Integer.parseInt(pieces[3]);
String photo = pieces[4];
Fruit f = new Fruit(id, name, grms, calories, photo);
fruitList.add(f);
}
}
}
Need to know the reason!
Check if your data is clean in the file (data.txt). It will not work if there is a single empty line or basically any line not in the desired format.
Example:
a12387beac8 Apple 1 1500 /location/photo.jpeg
I hope you are trying to split based on white space.
try this:
String[] pieces = line.split("\\s+");
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 8 months ago.
I have the following service for to get values inside a string document, this service is called inside a for, getting the data for every flight and then generate a PDF.
I'm getting the Index 2 out of bounds for length 1 when try to call the service, this is the code:
private Map<String, Object> readFileLsd(String content) {
Map<String, Object> mapResult = new LinkedHashMap<>();
try {
Reader inputString = new StringReader(content);
BufferedReader br = new BufferedReader(inputString);
String line;
String TotalBaggagesCargo = "";
String PASSENGER = "";
String TOTAL_TRAFFIC = "";
String validCharacters = "[\\x00-\\x1F]|[\\x21-\\x2c]|[\\x3B-\\x40]|[\\x5B-\\x60]|[\\x7B-\\xFF]";
while ((line = br.readLine()) != null) {
line = line.replaceAll(validCharacters, "").trim();
if (line.startsWith("LOAD IN COMPARTMENTS")) {
TotalBaggagesCargo = line;
}
if (line.startsWith("PASSENGER/CABIN BAG")) {
PASSENGER = line;
}
if (line.startsWith("TOTAL TRAFFIC LOAD")) {
TOTAL_TRAFFIC = line;
}
}
mapResult.put("TotalBaggagesCargo", TotalBaggagesCargo.trim().replaceAll("\\s+", " ").split(" ")[3]);
mapResult.put("PASSENGER", PASSENGER.trim().replaceAll("\\s+", " ").split(" ")[2]);
mapResult.put("TOTAL_TRAFFIC", TOTAL_TRAFFIC.trim().replaceAll("\\s+", " ").split(" ")[3]);
} catch (Exception e) {
e.printStackTrace();
}
return mapResult;
}
Underlying Problem
The line which starts with PASSENGER/CABIN BAG apparently has only one whitespace character and when you split it by a space it results in a String array with only one entry.
Possible solution
If the amount of passengers is sometimes not present in the input String, then you could make the put of key conditional.
String[] passengers = PASSENGER.trim().replaceAll("\\s+", " ").split(" ");
if (passenger.length > 2) mapResult.put("PASSENGER", passengers[2]);
This might bring different problems later in your program. So before working around it, you must try to understand, why it is absent. If it is reasonable that it is missing, then the workaround is acceptable, maybe you will need an else-case like that
else mapResult.put("PASSENGER", "");
when the key has to be present later on.
This question already has answers here:
Java: Reading a file into an array
(5 answers)
Closed 4 years ago.
i would like to build a text data-cleaner in Java, which
cleans the text from Smileys and other special charakter. I wrote a text reader,
but he stops after 3/4 of Line 97 and i just don't know why he does it? Normally he should read the complete text file (ca. 110.000 Lines) and then stop. It would be really nice if could show me where my mistake is.
public class FileReader {
public static void main(String[] args) {
String[] data = null;
int i = 0;
try {
Scanner input = new Scanner("C://Users//Alex//workspace//Cleaner//src//Basis.txt");
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
data[i] = line;
i++;
}
input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(data[97]);
}
}
Your mistake is here:
String[] data = null;
I would expect this code to throw null pointer exception...
You can use ArrayList instead of plain array if you want to have dynamic re-sizing
This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
i have wrote the code to read a 3rd column of a file(treeout1.txt) and write those contents in another file(tree.txt).and now i want to open tree.txt and write the contents to stem.txt,where tree.txt contents a single word in each row and a delimiter is found at the end of each line.i have attached that txt file below.you can view that to have better understanding.now i want to write the words into a line till a delimiter "###" is found...for example 'the girl own paper' and next line vol and so on....i have tried that but ArrayIndexOutOfBoundsException comes for a[]...why?and how to resolve that?
the text file tree.txt is given below
the
girl
own
paper
###
vol
###
viii
###
no
###
#card#
###
October
#card#
#card#
###
price
one
penny
###
as
the
baron
have
conjecture
the
housemaid
whom
he
have
call
out
of
the
nursery
to
look
for
###
lons
cane
on
find
her
master
have
go
without
it
do
not
hurry
back
but
stop
talk
###
Code:
package simple;
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Simple {
public static void main(String[] args) throws IOException {
String line;
String line2;
String[] a = new String[100];
int i = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("C:/TreeTagger/treeout1.txt"));
BufferedWriter output = new BufferedWriter(new FileWriter("D:/tree.txt"));
String separator = System.getProperty("line.separator");
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, "\n");
while (st2.hasMoreElements()) {
String line1 = (String) st2.nextElement();
String[] array = line1.split("\\s+", 3);
//System.out.println(array[2]);
output.append(array[2]);
output.newLine();
}
}
output.close();
br.close();
BufferedReader br1 = new BufferedReader(new FileReader("D:/tree.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("D:/stem.txt"));
while ((line2 = br1.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line2, " ");
while (st.hasMoreTokens()) {
String element = st.nextToken();
System.out.println(element);
while (element != "###") {
a[i] = element;
i++;
}
out.append(a[i]);
element = element.replace(element, "");
}
}
} catch (IOException e) {
}
}
}
You need to reset i to 0 after you find the ### delimiter. Otherwise you will keep incrementing i until it gets larger than 100 (a's maximum).
Also you can't use the != operator on Strings (from your code: element != "###"). You need to use the following:
!"###".equals(element);
This question already has answers here:
Adding only specific text from a file to an array list, part 2 - Java
(2 answers)
Closed 7 years ago.
I hope I can get here some help.
This is the text in my file:
Name: John
Name: Peter
Name: Sarah
Place: New York
Place: London
Place: Hongkong
How can I for example only add the names from the text file in the following arraylist?
So far, I've got... and it add everything in the arraylist, including places!
private ArrayList<Name> names = new ArrayList<>();
public void load(String fileName) throws FileNotFoundException {
String text;
try {
BufferedReader input = new BufferedReader(new FileReader(fileName));
while((text = input.readLine()) != null){
text = text.replaceAll("Name:", "");
names.add(new Name(text));
}
}
catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
At the end, it should only add the names in the Name ArrayLIst, like John, Peter, Sarah.
I would appreciate for any suggestions, thanks!
Add an if statement and look for strings with "Place", using a regex expression and knock this out. That is the easiest way.
But here is another simple solution. You can also add more words to look out for using the OR operator inside the if.
while((text = input.readLine()) != null){
//gets rid of places
if !(a.contains("Place")){
text = text.replaceAll("Name:", "");
names.add(new Name(text));
}
}
Try Splitting each line you have on the delimiter :, for instance:
String[] parts = text.split(":");
String part1 = parts[0]; // Name
String part2 = parts[1]; // John
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I populate JComboBox from a text file?
I am new to programming Java with only 2 months of experience. Can anyone help me to populate a JComboBox with a text file, consisting of 5 lines? I have looked at code on Google, but I keep getting errors.
private void populate() {
String[] lines;
lines = readFile();
jComboBox1.removeAllItems();
for (String str : lines) {
jComboBox1.addItem(str);
}
}
Here is readFile(). From this site
private String[] readFile() {
ArrayList<String> arr = new ArrayList<>();
try {
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
arr.add(strLine);
}
in.close();
} catch (Exception e) {
}
return arr.toArray(new String[arr.size()]);
}