Reading CSV file with different row length in java - java

I try to read all the lines from a CSV file, but not all the lines are the same length. I used this code:
BufferedReader reader = new BufferedReader(new FileReader("C://Users/Balazs/Downloads/numbers.csv"));
String line = "";
while ((line = reader.readLine()) != null) {
String[] szamok = line.split(";");
But if some rows are longer than the ones before, it gives me error.
Any ideas how to solve this in java?
Thanks!

if (szamok.length > 19) {
Integer hetedikSzam = Integer.parseInt(szamok[19]);
hetedikSzam = Integer.parseInt(szamok[19]);
}

Related

BufferedReader multiple lines as one String

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

BufferedReader skip lines assets file java android

I'm trying to read a .txt-file that's located in my assets folder in an Android project. Search the file, read the file with the InputStreamer and the BufferedReader works just fine, but the problem is: it doesn't read ALL the lines. So when I want to add a line to an ArrayList for further use, not all the lines are present in this list. This is my code:
InputStream inputStream;
BufferedReader br;
try {
inputStream = getResources().getAssets().open("KeyMapping.txt");
br = new BufferedReader(new InputStreamReader(inputStream));
final ArrayList<String> viewList = new ArrayList<String>();
String line = null;
//Add every line (except the first) to an arrayList
while ((line = br.readLine()) != null && (line = br.readLine()) != "1,2,3,4,5,6,7,8,char") {
viewList.add(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
The format of my .txt-file is like this:
1,2,3,4,5,6,7,8/char
1,,,,1,,,/a
2,,,,1,,,/b
3,,,,1,,,/c
,1,,,1,,,/d
,2,,,1,,,/e
,3,,,1,,,/f
,,1,,1,,,/g
,,2,,1,,,/h
,,3,,1,,,/i
,,,,1,,,1/j
,,,,1,,,2/k
,,,,1,,,3/l
1,,,,2,,,/m
2,,,,2,,,/n
3,,,,2,,,/o
,1,,,2,,,/p
,2,,,2,,,/q
,3,,,2,,,/r
,,1,,2,,,/s
,,2,,2,,,/t
,,3,,2,,,/u
,,,,2,,,1/v
,,,,2,,,2/w
,,,,2,,,3/x
...
Only a few of these lines will be added to the ArrayList, does anyone know why?
while ((line = br.readLine()) != null && (line = br.readLine()) != "1,2,3,4,5,6,7,8,char")
This line reads 2 lines from the stream, and processes the 2nd line always.
Also, you cannot compare strings with != operator. Use String.equals() method.
while ((line = br.readLine()) != null)
{
if(line.equals("1,2,3,4,5,6,7,8,char"))
continue;
//add if it's not that string
viewList.add(line);
}

How to read data from System.in to solve the task?

I'm working on this item. I did the spell checking algorithm but I have no idea how to read data correctly. When I use this:
StringBuilder text = new StringBuilder();
Scanner sc = new Scanner(System.in);
String temp;
while ((temp = sc.nextLine()).length() > 0){
text.append(temp);
}
/*spell checking algorithm*/
It waits for the empty string.
In this case:
while (sc.hasNext()){
text.append(temp);
}
it doesn't continue to execute the code at all. If I try to read 10000 signs I should type it all.
How could I read data correctly for this task?
Read them from file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
//do what you want
}

Regular expression illegal character in Java

I've been looking through the Internet an after a big headache, cannon't find why this regular expression is wrong:
"\"\w*&&[\p{Punct}]\"["+sepChar+"]\"\w*&&[\p{Punct}]\""
I'm trying to read a master data file with the following pattern (quotes included):
"TEXTVALUE":"TEXTVALUE":"TEXTVALUE"
and split each line with the regular expression above.
So, for example:
"Hello:John":"Hello:World":"Hello:Mark"
will be splitted into:
{"Hello:John", "Hello:World", "Hello:Mark"}
The backwards slash is the escape character in Java. You need to use two backslashes \\ to include a single backslash in the regex.
Try:
"\"\\w*&&[\\p{Punct}]\"["+sepChar+"]\"\\w*&&[\\p{Punct}]\""
Ok.
Thanks to #kevin-bowersox for the help.
It seems that Oracle has done a great job improving Java with version 7.
With this code:
File file = new File(someFile);
BufferedReader br = new BufferedReader(file);
String line = null;
while((line = br.readLine()) != null){
//todo
}
If your file has been formatted with a constant patern, for example:
"TEXTVALUE":"TEXTVALUE":"TEXTVALUE"
It reads:
"TEXTVALUE-->TEXTVALUE-->TEXTVALUE"
where '-->' stands for tabs ('\t')
So, at the end, my solution is:
public ArrayList getSplittedTextFromFile(String filePath) throws FileNotFoundException, IOException{
ArrayList<String[]> ret = null;
if (!filePath.isEmpty()){
File input = new File(filePath);
BufferedReader br = new BufferedReader(input);
String line = null;
while((line = br.readLine()) != null){
String[] aSplit = line.split("\\t");
if (ret == null)
ret = new ArrayList<>();
ret.add(aSplit);
}//while
}//fi
}//fnc

BufferedReader() returning empty string when there are more strings in the file?

My txt file looks like this:
data;data2;data3;data4..........up till data3146
When I open the txt file in notepad I see it in the form given above.
But when I copy paste the first few lines to another place, There is a 1 line gap b/w data1 and everything else. Because of this I am getting problems while accessing the file in Java and using the data with a bufferedreader in a loop. How can I correct this? I can't remove the empty line as it is not even visible in the original file.
You can ignore the blank line(s). Something like this -
while ((line = reader.readLine()) != null) {
if(line.trim().isEmpty()) {
continue;
}
...
you can try this way:
BufferedReader reader = new BufferedReader(new FileReader(new File("your file path")));
String str = null;
while((str = reader.readLine())!=null) {
if (str.matches("[' ']+")) {
continue;
} else {
// to do
}
}
I believe that the problem is in the line endings. Basically you can skip the empty lines:
String line;
while ((line = reader.readLine()) != null) {
if ("".equals(line.trim()) {
continue;
}
// do your stuff here
}

Categories