Convert .csv into a list of arrays - java

I am reading in a csv file that contains a transport route.
I have the file displaying in the terminal window.
I would like to create a new array for each journey.
The first row of the file is the stop name,then each row after that contains the registration of the vechicle,the time at which the journey starts at stop 1 and the time to get to the next stop(s).
So a journey would consist of the vehicle registration,the stop name and the time when the vehicle should be there.
Example
Stop "Stop1" "Stop2" "Stop3"
-------------------------------
R101 650 4 7
R101 710 4 6
R101 730 4 9

If you don't want to use a library you can create a utility method that will convert a CSV into a list of arrays like so;
public static List<String[]> csvToListOfArrays(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
List<String[]> arrays = new ArrayList<String[]>();
String line;
while ((line = reader.readLine()) != null) {
String[] tokens = line.split(",");
arrays.add(tokens);
}
return arrays;
}
In the code above, we create a buffered reader and use the readLine() method to get each line of the CSV one at a time. Then, when we have that line, we call split(",") to split the line into an array of strings on the commas. Lastly, we add the arrays to a list for use later.

Related

Trouble reading a file in java in a certain format

I am reading text from a file and I have been having trouble trying to read List 1 and List 2 into 2 different String . The * indicates where the first list ends. I have tried using arrays but the array only stores the last * symbol.
List 1
Name: Greg
Hobby 1: Swimming
Hobby 2: Football
*
List 2
Name: Bob
Hobby 1: Skydiving
*
Here's what I tried so far:
String s = "";
try{
Scanner scanner = new Scanner(new File("file.txt"));
while(scanner.hasnextLine()){
s = scanner.nextLine();
}
}catch(Exception e){
e.printStackTrace}
String [] array = s.split("*");
String x = array[0];
String y = array[1];
Your code has multiple issues like #Henry said that your string contains only the last line of the file and also you misunderstood the split() because it takes a RegularExpression as a parameter.
I would recommend you to use the following example because it works and is a lot faster than your approach.
Kick-Off example:
// create a buffered reader that reads from the file
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
// create a new array to save the lists
ArrayList<String> lists = new ArrayList<>();
String list = ""; // initialize new empty list
String line; // initialize line variable
// read all lines until one becomes null (the end of the file)
while ((line = reader.readLine()) != null) {
// checks if the line only contains one *
if (line.matches("\\s*\\*\\s*")) {
// add the list to the array of lists
lists.add(list);
} else {
// add the current line to the list
list += line + "\r\n"; // add the line to the list plus a new line
}
}
Explanation
I'm going to explain special lines that are hard to understand again.
Looking at the first line:
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
This line creates a BufferedReader that is nearly the same like a Scanner but it's a lot faster and hasn't as much methods as a Scanner. For this usage the BufferedReader is more than enough.
Then it takes an InputStreamReader as a parameter in the constructor. This is only to convert the following FileInputStream to a Reader.
Why should one do that? That's because an InputStream ≠ Reader. An InputStream returns the raw values and a Reader converts it to human readable characters. See the difference between InputStream and Reader.
Looking at the next line:
ArrayList<String> lists = new ArrayList<>();
Creates a variable array that has methods like add() and get(index). See the difference of arrays and lists.
And the last one:
list += line + "\r\n";
This line adds the line to the current list and adds a new line to it.
"\r\n" Are special characters. \r ends the current line and \n creates a new line.
You could also only use \n but adding \r in front of it is better because this supports more Os's like Linux can have problems with it when \r misses.
Related
Using BufferedReader to read Text File

Reading a file and performing functions based on the contents of the line

I'm wondering if it's possible to read a file by the line number, each with different values and make a condition where if that line contains a certain string or number specified. If it did it would, for example, take the content specified in that line into a variable?
So in a file line one has Age: 50, line 2 has Age: 23, line 3 has Age: 34. What I'm hoping for is that I look specifically at line 3 and take the number 34 and place it in a variable for use in my program.
If it is possible, how would you go about doing this?
I would say, it is not possible to directly address a specific line unless - perhaps you know the line sizes of your file, etc... to seek through the file. But you can use this to go through your file, line by line:
String line;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
// do some cool stuff with this line.
}
br.close();
Possible duplicate: Reading a file and performing functions based on the contents of the line
You can always iterate through each line, keeping track of the line via an int or a short.
some code:
String line;
BufferedReader br = new BufferedReader(new FileReader(FILE_HERE));
int line = 0;
while ((line = br.readLine()) != null) {
line++;
if(line == 3){
//do whatever you want
}
}
br.close();
I will add that getting something from one single line while others also have identical info is bad
you can use the scanner object to read through a file. you would use the delimiter to find the info you want and a counter to keep track of the line, then put it in an arraylist or something. depending on what you want to do.
Scanner in = new Scanner(filename);
int line = 0;
in.useDelimiter("[regex of the info you are looking for]");
while in.hasNext()) {
line++
//do something
}

Android 2d array from text file

So what I'm trying to do is I have a text file that has 5580 lines and then has 9 columns separated by a , . I'm trying to have the user input an entry that will be in the first column and I need to search for that entry and pull the rest of the information. Java is new to me (I'm starting to miss fortran or python) any help?
Learn about input streams and readers. Here is some code sample that can be used by you to start.
String token = // init it
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileReader(thefileName)));
for (String line = reader.nextLine(); line !=null; line = reader.nextLine()) {
String[] parts = line.split(",");
if (token.equals(parts[0])) {
// this is the line you are looking for...
}
}

Detected a new line within a series of numbers in Java

Let's say I have a series of numbers like...
1 2 3 4
5 6 7 8
9 0
How could I step through each int, but stop when I reach a new line? I'm currently using nextInt() and I know that nextLine() will detect the new line, but I'm not sure how to piece that together. Is it best to take the entire line, and parse the string into separate ints? Or is there a more fluid method of doing this?
For my example, I would want the program to store 1 2 3 4, 5 6 7 8, 9 0 all in their own separate array.
For more clarification, I'm using the java.util.Scanner and I'm reading a text file.
If you want to use Scanner, read the entire line into a String, and then construct a Scanner on the String.
You can open the text file in read mode and read the entire line with readLine() method.
Then you can split the line read with the space ( ' ' ) character which will automatically give you an array.
You can do this till the end of file.
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
delimiter = " ";
int myArr[];
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
myArr = strLine.split(delimiter);
// store this array into some global array or process it in the way you want.
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Hope this helps.

read lines in txt file [java] [duplicate]

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

Categories

Resources