Java - Trouble reading CSV to Array - java

I'm trying to read a .csv file to an array, and then parse the row on commas, to pull out specific numbers from my file. I'm not getting any errors, and the program runs fine, however it won't let me pull from anything other than thisLine[0]. There should be 3 elements in the line.
The csv looks something like this:
32.34553,-122.4535636,-118.1
32.34553,-122.4535536,-118.1
32.34553,-122.4512236,-118.1
32.34553,-122.4515466,-118.1
32.34553,-122.4532336,-118.1
When I try to call thisLine[1] (which should be something like '-122.4535636') I get :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at com.mkyong.util.ReadCSV.run(ReadCSV.java:32)
at com.mkyong.util.ReadCSV.main(ReadCSV.java:14)
I'm really new to Java so I'm sorry if this is a simple fix. Thanks for any help,
package com.mkyong.util;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadCSV {
public static void main(String[] args) {
ReadCSV obj = new ReadCSV();
obj.run();
}
public void run() {
String csvFile = "C:/Program Files/EDX/Projects/Brisbane, CA R900/Data/GIS/meters.csv";
BufferedReader br = null;
String line = "";
String csvSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) !=null) {
String[] thisLine = line.split(csvSplitBy);
System.out.println("The Current Line is: " + thisLine[0] + ", " + thisLine[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br !=null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}

Related

I can't write on multiple lines in a txt file in java

So I'm trying to write in a text file, nothing too complicated, but for some reason the new text that i want to add doesn't change lines, it keeps going on the same line, and I can't figure out why. The irrelevant parts are being commented so don't worry about them.
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
public class Main {
public static void main( String args[]) {
int a = 32;
int b=12;
int c=33;
List<Integer> myList = new ArrayList();
myList.add(a);
myList.add(b);
myList.add(c);
/* for(int s:myList)
{
System.out.println(s);
}
*/
//Om ar= new Om("Alex",21,185);
//System.out.println(ar);
try{
File myObj = new File("filename.txt");
if(myObj.createNewFile()){
System.out.println("File created " + myObj.getName());
}
else
{
System.out.println("File already exists");
}
}
catch (IOException e)
{
System.out.println("An error has occurred");
e.printStackTrace();
}
try {
FileWriter myWriter = new FileWriter("filename.txt");
for(int i=1;i<10;i++)
{
myWriter.append("This is a new file, nothing sus here."+i + " ");
}
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Wrap your FileWriter in a BufferedWriter to make writing to the file more efficient.
Then you can use the newLine() method of the BufferedWriter to add a newline String to the file as you require. The newLine() method will write out the appropriate string for your current platform.

Buffered reader causing an infinite loop

I'm currently doing a test project to understand how to read/write into a text file. This is my code:
package testings;
import java.util.Scanner;
import java.io.*;
public class Writing_Reading_files {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
File testFile = new File("testFile.dat");
String test, sName;
try{
PrintWriter print = new PrintWriter(new BufferedWriter(new FileWriter(testFile)));
test = in.nextLine();
print.println(test);
print.close();
}catch(IOException e) {
System.out.println("IO exception");
System.exit(0);
}
try {
BufferedReader readerName = new BufferedReader(new FileReader(testFile));
while(readerName != null) {
sName = readerName.readLine();
System.out.println(sName);
}
readerName.close();
} catch(FileNotFoundException e) {
System.out.println("FileNotFound");
System.exit(0);
} catch(IOException e) {
System.out.println("IO exception");
System.exit(0);
}
}
}
The while loop results in spitting out the line I put then nulls for an infinite loop if I try While(readerName.readLine != null) it stops the infinite loop but only outputs a null and I don't know where to go from there, I've tried following a youtube tutorial but he has it the same as my code so I'm unsure why I'm null keeps repeating. Thanks in advance for any help.
why would readerName become null? Maybe you mean that the String returned by readLine is null?
Consider
BufferedReader readerName = new BufferedReader(new FileReader(testFile));
String sName = readerName.readLine();
while(sName != null) {
System.out.println(sName);
sName = readerName.readLine();
}
Also consider using try-with-resources when opening your file.

Program in java that reads data from a text file

date time kg
12/10/2013 00.00.01 1
13/11/2013 00.00.05 2
17/12/2013 00.00.90 5
21/12/2013 00.00.23 6
27/12/2013 00.00.43 9
I have these data in an txt file. I would like to make o program in java that would read these data. I ' ve written the code above but I have mistakes. Could someone help me? The data have space between each other.
import java.io*;
public class ReadTextfile{
public static void main (String[] args) {
File file = new File ("test.txt");
StringBuilder line = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(file));
String text = null;
while ((text = reader.readLine()) !=null) {
line.append(text)
.append(System.getProperty ("line.separator"));
}
}
catch (IOException e) {
e.printStackTrace();
catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (reader !=null){
reader.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(line.toString());
}
}
boy you are only having some syntax problem
1 : replace
import java.io* with import java.io.*
2 : take care of your catch body being started and closed properly
try
{
// your code
}
catch(Exception e)
{
}
here is the working code , compare your program
import java.io.*;
public class ReadTextfile{
public static void main (String[] args)
{
File file = new File ("C:/Users/hussain.a/Desktop/test.txt");
StringBuilder line = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(file));
String text = null;
while ((text = reader.readLine()) !=null) {
line.append(text)
.append(System.getProperty ("line.separator"));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
if (reader !=null){
reader.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println(line.toString());
}
}
catch (FileNotFoundException e)
This is unreachable code, since above it you caught IOException.
Note that:
public class FileNotFoundException extends IOException
Your code won't compile. Remove this catch (You didn't even close it..)
Another thing, if this is not a type, you should replace java.io* with import java.io.*.
I would take the following approach:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadTextFile
{
public static void main(String[] args) throws FileNotFoundException
{
File file = new File("test.txt");
Scanner scanner = new Scanner(file);
List<Result> results = new ArrayList<Result>();
while(scanner.hasNextLine())
{
String currentLine = scanner.nextLine();
String [] resultArray = currentLine.split(" ");
results.add(new Result(resultArray[0], resultArray[1], resultArray[2]));
}
scanner.close();
}
private static class Result
{
private String date;
private String time;
private String kg;
public Result(String date, String time, String kg)
{
super();
this.date = date;
this.time = time;
this.kg = kg;
}
public String getDate()
{
return date;
}
public String getTime()
{
return time;
}
public String getKg()
{
return kg;
}
}
}
Now you can pull out any information that you want to from the list of results that you have.
So if you wanted to print everything, you could do the following:
for(Result singleResult : results)
{
System.out.println(singleResult.getDate() + " " + singleResult.getTime() + " " + singleResult.getKg());
}
You basically can do whatever you want to with the data. This approach would also allow you to transform the data into different types before you even create the Result object.

Running grep From Java Program

I've spent the past 3 days without much luck on google on how to run a grep process from within Java.
I have the following code to run a grep process, however, I am only getting the first line of the response.
package com.example.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
Process process = new ProcessBuilder("grep", "-rni", "\"public static void main(\"", "/home/user/dev/java/").start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("Exit Code: " + process.exitValue());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am only getting the following response:
Binary file /home/user/dev/java/Parser/parser/bin/com/example/parser/Main.class matches
Exit Code: 0
When I should be getting the following response:
Binary file /home/user/dev/java/Parser/parser/com/example/parser/Main.class matches
/home/user/dev/java/Parser/parser/src/com/example/parser/Main.java:10: public static void main(String[] args) {
/home/user/dev/java/Parser/parser/src/com/example/parser/Main.java:12: Process process = new ProcessBuilder("grep", "-rni", "\"public static void main(\"", "/home/user/dev/java/Parser/parser").start();
Exit Code: 0
I am wondering why I only get output for the first finding? Is grep forking several processes to run the search and I'm only getting a handle on the first one?
I have also tried running the process from a Thread:
package com.example.parser;
public class Main {
public static void main(String[] args) {
try {
Analyzer analyzer = new Analyzer();
analyzer.start();
analyzer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.example.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Analyzer extends Thread {
public Analyzer() {
}
#Override
public void run() {
try {
Process process = new ProcessBuilder("grep", "-rni", "\"public static void main(\"", "/home/user/dev/java/Parser/parser").start();
process.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("Exit Code: " + process.exitValue());
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
As well as the following:
package com.example.parser;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
Process process = new ProcessBuilder("grep", "-rni", "\"public static void main(\"", "/home/user/dev/java/Parser/parser").start();
process.waitFor();
Analyzer analyzer_is = new Analyzer(process.getInputStream());
Analyzer analyzer_es = new Analyzer(process.getErrorStream());
analyzer_is.start();
analyzer_es.start();
analyzer_is.join();
analyzer_es.join();
System.out.println("Exit Code: " + process.exitValue());
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.example.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Analyzer extends Thread {
InputStream is = null;
public Analyzer(InputStream is) {
this.is = is;
}
#Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(this.is));
String line = "";
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
As suggested by the following article: http://www.javaworld.com/jw-12-2000/jw-1229-traps.html
I was able to solve the issue by launching a shell with the -c flag. The following code does what I had originally intended:
package com.example.parser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
try {
List<String> commands = new ArrayList<String>();
commands.add("/bin/sh");
commands.add("-c");
commands.add("grep -rni --include \"*.java\" \"public static void main(\" /home/user/dev/java/Parser/parser");
Process process = new ProcessBuilder(commands).start();
Analyzer analyzer_is = new Analyzer(process.getInputStream());
Analyzer analyzer_es = new Analyzer(process.getErrorStream());
analyzer_is.start();
analyzer_es.start();
process.waitFor();
analyzer_is.join();
analyzer_es.join();
System.out.println("Exit Code: " + process.exitValue());
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.example.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Analyzer extends Thread {
InputStream is = null;
public Analyzer(InputStream is) {
this.is = is;
}
#Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(this.is));
String line = "";
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is probably because you don't wait for the grep to finish.
Use the waitFor method :
Process process = new ProcessBuilder("grep", "-rni", "\"public static void main(\"", "/home/user/dev/java/").start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
process.waitFor();
String line = "";
while((line = br.readLine()) != null) {
System.out.println(line);
}
Note that you may also read the output (mainly to get what happens) while it is being processed using
Process process = new ProcessBuilder("grep", "-rni", "\"public static void main(\"", String line;
while (true) {
line = reader.readLine(); // add IO exception catching
if (line != null) {
System.out.println(line);
} else {
Thread.sleep(DELAY); // DELAY could be 100 (ms) for example
}
}
I suppose you're sure a grep launched by the owner of the java program is more than one line long ?
The other reason could be your process is still running but your Java program just exited.
Use the process.waitFor(); and Read your input stream in a thread.
Start the process.
Lunch a thread with the process input stream as the input.
Now wait for the process to exit by using process.waitFor();
This might help!
Have a look at this project for grep in java https://code.google.com/p/grep4j

Problem getting output and passing input to a executing process running under java

I am trying to call a simple program test.exe which is as simple as-
int main()
{
int a;
cout<<"Welcome\n";
while(cin>>a&&a!=0)
cout<<"you entered "<<a<<endl;
}
I want to run it from a java program as a process, and send+recieve i/o from it. I am using the process with 2 threads as follows-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Processproblem {
public static void main(String[] args)throws IOException, InterruptedException {
final Process process;
try {
process = Runtime.getRuntime().exec("test.exe");
} catch (IOException e1) {
e1.printStackTrace();
return;
}
new Thread(new Runnable() {
public void run() {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
try {
while ((line = br.readLine()) != null) {
System.out.println("[OUT] " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
byte[] buffer = new byte[1024];
int reading=0;
System.out.println(reading);
BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
while(reading!=-1)
{
reading= System.in.read(buffer);
for(int i = 0; i < buffer.length; i++) {
int intValue = new Byte(buffer[i]).intValue();
if (intValue == 0) {
reading = i;
break;
}
else
{
bw.append((char)intValue);
}
}
bw.newLine();
bw.flush();
}
} catch (Exception e) {
}
}
}
).start();
}
}
But they are not working as expected. When i run the program it just shows the "Welcome\n" message and then stops for input. When i give a integer and press enter in the java console it does nothing.
What am I doing wrong? They are two separate threads so why are they blocking each other? Is there any problem in my concept?
The program waits for your input. Grab the process output stream (using getOutputStream) and write to it.

Categories

Resources