Print specific lines(Words/numbers) from csv file - java

Lets say I have CSV file like this:
Football Contest blabla bla,,,,,,,
Team number1,Team number2,Points team1,Points team2,Red cards
Sweden,France,1,2,"
Sweden,Brazil,3,5,2
Sweden,Germany,2,2,3
Sweden,Spain,3,5,"
And in this file I only want to print out the matches that got red cards. So in this example I would like to print:
Sweden - Brazil = 2 Sweden - Germany = 3
This is my current code, and Im stuck how to move on.
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String lines = br.readLine();
String result[] = lines.split(",");
do{
System.out.println();
}while((lines = br.readLine()) != null);
//String result[] = lines.split(",");
//System.out.println(result[1]);
br.close();
}catch (FileNotFoundException e){
System.out.println("File not found : "+ file.toString());
}catch (IOException e ){
System.out.println("Unable to read file: "+ file.toString());
}
EDIT I got helped with:
while (line != null) {
String result[] = line.split(",");
if (result.length == 5) { //red cards present?
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}
line = br.readLine(); //read next
}
But the problem I have now is that it still prints all because of the " in the csv file. Why cant I do something like this?
if (result[4] == "1,2,3,4,5" ){
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}

If you the index of red card and it looks like Integer, Then see for that index is integer or not if Yes the print 0,1 and 4
index[0]=Team number1
index[1]=Team number2
index[4]=red cards

Your try-catch block should look like this:
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
String result[] = line.split(",");
if (result.length == 5 && result[4].matches("[0-9]")) { //red cards present?
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}
line = br.readLine(); //read next
}
//close readers
br.close();
fr.close();
} catch (FileNotFoundException e) {
System.out.println("File not found : " + file.toString());
} catch (IOException e) {
System.out.println("Unable to read file: " + file.toString());
}
If there are trailing whitespaces in your file, you have to trim the String first: result[4].trim().matches("[0-9]") or use another regex: result[4].matches("\\d\\s")

Why cant I do something like this?
if (result[4] == "1,2,3,4,5" ){
The problem with this is == tests for identity: it will compare if the reference in result[4] is the same reference as the constant in your source code. That expression will always be false. You need to check for equality, not identity:
if (Objects.equals(result[4], "1,2,3,4,5")) {
or
if (result[4] != null && result[4].equals("1,2,3,4,5")) {
or
if ("1,2,3,4,5".equals(result[4])) {
Note that Objects.equals() was (finally) added to the Java standard library in Java 8. Without it, you must guard against a NullPointerException before you call the .equals() method on an object. Traditionally I have preferred the last version because invoking the method on the string literal means I can be assured it is never null and will just work.

You can try like this
public class HelloWorld{
public static void main(String []args){
String str1= "Sweden,Brazil,3,5,4";
String str2="Sweden,Germany,2,2,3";
String str3="Football Contest blabla bla,,,,,,,";
String result1[]=str1.split(",");
String result2[]=str2.split(",");
String result3[]=str3.split(",");
if(result1.length>=5){
System.out.print(result1[0]+"-"+result1[1]+"="+result1[4]);
System.out.println();
}
if(result2.length>=5){
System.out.print(result2[0]+"-"+result2[1]+"="+result2[4]);
System.out.println();
}
if(result3.length>=5){
System.out.print(result3[0]+"-"+result3[1]+"="+result3[4]);
System.out.println();
}
}
}

try this:
do {
if (result[4] instanceof Integer) {
System.out.print(result[0]+"="+result[1]+"="+result[4])
}
} while ((lines = br.readLine()) != null);

Related

Java read specific parts of a CSV

I created the following code to read a CSV-file:
public void read(String csvFile) {
try {
File file = new File(csvFile);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
String[] tempArr;
while((line = br.readLine()) != null) {
tempArr = line.split(ABSTAND);
anzahl++;
for(String tempStr : tempArr) {
System.out.print(tempStr + " ");
}
System.out.println();
}
br.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
I have a CSV with more than 300'000 lines that look like that:
{9149F314-862B-4DBC-B291-05A083658D69};Gebaeude;TLM_GEBAEUDE;;Schiessstand;{41C949A2-9F7B-41EE-93FD-631B76F2176D};Altdorf 300m;offiziell;Hochdeutsch inkl. Lokalsprachen;Einfacher Name;;684600;295930;400
How can I now only get the some parts out of that? I only need the bold/italic parts to work with.
Without further specifying what your requirements/input limitations are the following should work within your loop.
String str = "{9149F314-862B-4DBC-B291-05A083658D69};Gebaeude;TLM_GEBAEUDE;;Schiessstand;{41C949A2-9F7B-41EE-93FD-631B76F2176D};Altdorf 300m;offiziell;Hochdeutsch inkl. Lokalsprachen;Einfacher Name;;684600;295930;400";
String[] arr = str.split("[; ]", -1);
int cnt=0;
// for (String a : arr)
// System.out.println(cnt++ + ": " + a);
System.out.println(arr[6] + ", " + arr[15] + ", " + arr[16]);
Note that this assumes your delimiters are either a semicolon or a space and that the fields desired are in the fix positions (6, 15, 16).
Result:
Altdorf, 684600, 295930

Java Reading text from a file then coverting it to morse

Java 11.6
I am trying to write a java class that will take in a filename as a parameter then read line by line of that file. After it is done reading it will convert the file to equivalent morse code. My other methods such as "print morse table" "convert string to morse" works as it should but for the file function, every time I type the file name it just gives me an empty output. Not sure where exactly is the problem. I am posting the method underneath.
public void encodeFile(String s){
try{
BufferedReader br = new BufferedReader(new FileReader(s));
while((br.readLine()) != null){
String st="";
if( st ==" "||st==null){
System.out.println("");
}else{
int length = st.length();
for(int i=0;i<length;i++){
char c = st.charAt(i);
int x = c;
if(x>96 && x<123){
c = Character.toUpperCase(c);
}
if(c==' '){
System.out.printf(" ");
}else{
for(int j=0; j<listCodes.length; j++){
if(c==listCodes[j].getCharacter()){
System.out.printf(listCodes[j].getEncoding() + " ");
break;
}
if(listCodes[j+1]==null){
System.out.printf("?");
break;
}
}
}
}
}
System.out.printf("%n");
}
br.close();
}catch (Exception e){
System.out.println("java.lang.Exception: Invalid File Name: " + s);
}
}
The problem is that you are not storing the value of br.readLine() into st. Apart from this, you should use .equals instead of == to compare two strings.
Do it as follows:
public void encodeFile(String s){
try{
BufferedReader br = new BufferedReader(new FileReader(s));
String st="";
while((st = br.readLine()) != null){ // Store the value of `br.readLine()` into `st` and check if it is not null
if(st.equals(" ")){ // You need not check `st` for null again.
System.out.println("");
}else{
//...
}
//...

java.lang.ArrayIndexOutOfBoundsException how to remove this error?

how do I get rid of the ArrayIndexOutOfBoundsException?
Here is the code that triggers the exception:
FileReader fr;
try {
System.out.println(4);
fr = new FileReader("SOME FILE PATH");
BufferedReader br = new BufferedReader(fr);
String in ;
while (( in = br.readLine()) != null) {
String[] lines = br.readLine().split("\n");
String a1 = lines[0];
String a2 = lines[1];
System.out.println(a2 + " dsadhello");
a11 = a1;
String[] arr = a11.split(" ");
br.close();
System.out.println(arr[0]);
if (arr[0].equals("echo")) {
String s = a11;
s = s.substring(s.indexOf("(") + 1);
s = s.substring(0, s.indexOf(")"));
System.out.println(s);
save++;
System.out.println(save + " save numb");
}
}
System.out.println(3);
} catch (FileNotFoundException ex) {
System.out.println("ERROR: " + ex);
} catch (IOException ex) {
Logger.getLogger(game.class.getName()).log(Level.SEVERE, null, ex);
}
and heres the file I'm pulling from:
echo I like sandwiches (hello thee it work)
apples smell good
I like pie
yes i do
vearry much
Exception is likely to be generated from the below line:
String a2 = lines[1];
We are using br.readLine() to read from file. This method reads only one line and returns it as a String. As it is only one line, it won't have '\n' and hence, splitting it with '\n' will result in an array with only one element (i.e. 0).
To make it work, we need to replace the below lines:
String[] lines = br.readLine().split("\n");
String a1 = lines[0];
String a2 = lines[1];
System.out.println(a2 + " dsadhello");
with
String a1 = in;
We don't need a2 here and we are already reading the line in while loop. There is no need to read it again.
In this part
String in;
while ((in = br.readLine()) != null) {
String[] lines = br.readLine().split("\n");
String a1 = lines[0];
String a2 = lines[1];
System.out.println(a2 + " dsadhello");
a11 = a1;
you read a line and ignore it, then read another line and tried splitting it by "\n". Unfortunately, there will be not \n in what is returned by br.readLine(), therefore lines will have only one elment and acceccing line[1] become illegal.
Intead of this, you can simply write
while ((all = br.readLine()) != null) {

BufferedReader - count lines containing a string

I am using a .txt file that contains: "Hello world\nHow are you doing this day?" I want to count whether a line contains a string or not, as well as the total number of lines. I use:
File file = new File(file_Path);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int i=0;
int j=0;
while ((line = br.readLine()) != null) {
j++;
if (line.contains("o")) { //<----------
i++;
}
}
System.out.print("Lines containing the string: " + i + " of total lines " + j-1);
As I run and test line.contains("o"), it prints 2 lines containing "o", which is correct as well as 2 total lines. As I run line.contains("world"), it prints 0 lines which is wrong but gives 2 lines total. But what do I do wrong?
I tested it with a StringReader,
String str = "Hello world\nHow are you doing this day?";
StringReader sr = new StringReader(str);
try {
BufferedReader br = new BufferedReader(sr);
String line;
int i = 0;
int j = 0;
while ((line = br.readLine()) != null) {
j++;
if (line.contains("world")) { // <----------
i++;
}
}
System.out
.println("Lines containing the string: " + i
+ " of total lines " + j);
} catch (Exception e) {
e.printStackTrace();
}
Your file contents must not be what you think because I get
Lines containing the string: 1 of total lines 2
As the others answers and comments, I also think you may not be reading the file you think you are... (Relax it happens to everyone from time to time)
But, also it could be the encoder of the file or the version of the jdk you have, maybe if you could answer:
What did you use to create the file?
What OS you are running
this?
What JDK are you using?
It could clarify what may have happened
Just for you to know, I ran the same code you have using jdk8 and worked fine for me.
As follows the test I did:
1) I put your code in a function:
int countLines(String filename, String wording) {
File file = new File(filename);
String line;
int rowsWithWord = 0;
int totalRows = 0;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while ((line = br.readLine()) != null) {
totalRows++;
if (line.contains(wording)) {
rowsWithWord++;
}
}
} catch (IOException e) {
System.out.println("Error Counting: " + e.getMessage());
}
System.out.println(String.format("Found %s rows in %s total rows", rowsWithWord, totalRows));
return rowsWithWord;
}
2) and ran the following unit test
#Test
public void testFile() {
try (FileWriter fileWriter = new FileWriter(new File("C:\\TEMP\\DELETE\\Hello.txt"));
BufferedWriter writer = new BufferedWriter(fileWriter)) {
writer.write("Hello world\nHow are you doing this day?");
} catch (IOException e) {
System.out.println("Error writing... " + e);
}
int countO = fileUtils.countLines("C:\\TEMP\\DELETE\\Hello.txt", "o");
Assert.assertEquals("It did not find 2 lines with the letters = o", 2, countO);
int countWorld = fileUtils.countLines("C:\\TEMP\\DELETE\\Hello.txt", "world");
Assert.assertEquals("It did not find 1 line with the word = world", 1, countWorld);
}
And I got the expected result:
Found 2 rows in 2 total rows
Found 1 rows in 2 total rows

Why do i get a NullPointerException at If statement in do while loop when reading a simple textfile in Java

I'm new in Java, I have a lot of work with text and I've got an idea to make a simple program to do my work. I'm getting error Exception in thread "main" java.lang.NullPointerException at com.text.work.Main.main(Main.java:25)
public class Main {
public static void main(String[] args) throws IOException {
int someNumber = 0;
PrintWriter saveFileOne = new PrintWriter("save.txt");
PrintWriter saveFileTwo = new PrintWriter("otherThings.txt");
FileReader fileReader = new FileReader("read.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String word = bufferedReader.readLine();
do {
word = bufferedReader.readLine();
if (word.toString().equals("true")) { //this is line 25
saveFileOne.println("No: " + ++someNumber + " = " + word);
} else {
saveFileTwo.println("Yes: " + someNumber + " = " + word);
}
} while (word != null);
saveFileOne.close();
saveFileTwo.close();
bufferedReader.close();
System.out.println("Done!");
}
}
From the BufferedReader#readLine() documentation:
Returns: A String containing the contents of the line, not including
any line-termination characters, or null if the end of the stream has
been reached
This means you've obviously reached the end of the stream.
If I were you, I would change the loop with a while one.
while ((word = buffer.readLine()) != null) {
..
}
Obviously word is null because bufferedReader.readLine() encountered the end of the stream and returned null.
You should do the check against null before entering the while body
while(null != (word = bufferedReader.readLine())) {
}
and to avoid such NPEs in general while comparing with constants call equals this way:
"true".equals(other string) // "true" is never null
Make sure that word is not null. Change the code as following code snippet.
do {
word = bufferedReader.readLine();
if(word != null) { //If word is null, no need to go in if block
if (word.toString().equals("true")) {
saveFileOne.println("No: " + ++someNumber + " = " + word);
} else {
saveFileTwo.println("Yes: " + someNumber + " = " + word);
}
}
} while (word != null);
You can also change your loop for reading a file can done easily using following code
if(buffer != null) {
while ((word = buffer.readLine()) != null) {
if (word.toString().equals("true")) {
saveFileOne.println("No: " + ++someNumber + " = " + word);
} else {
saveFileTwo.println("Yes: " + someNumber + " = " + word);
}
}
}
I've the same problem today, two addidional brackets is the answer
(word = bufferedReader.readLine()) != null)

Categories

Resources