How can i get the data for .csv File? [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
how to use .csv file in android?
i created a sample Android application, in this i used .csv file to store the data. I placed this file in my assetsfolder.
In my .csv file contains,
1 Indonesia Jakarta Phnom Penh New Delhi
2 Bosnia Pristina Sarajevo Prague
3 Germany Frankfurt Bonn Berlin
4 Kenya Kinshasa Nairobi Pretoria
5 Colombia Lima Buenos Aires Bogota
how can i get the values for the .csv file using java code..

You need to read in the file line by line and split each line by a separtor.
Basically like this:
try {
File f = new File("yourpath");
BufferedReader b = new BufferedReader( new FileReader( f ) ) );
String line = null;
while ( (line = b.readLine() ) != null ) {
String[] cells = line.split( "\t" ); //assuming the separator is a tab
//do whatever you want, e.g. collect the arrays into a list etc.
}
} catch( IOException e) {
//do whatever is appropriate
}

Its quite simple to parse such a file using a StringTokenizer.
Lets assume you have the file opened and you are reading a single line at a time. To break up the string into tokens with each token representing a word you could do the following:
String lineOfText; // This contains the current line of text
StringTokenizer st = new StringTokenizer(input, ", "); // ' ' and ',' are use as delimiters to break up the line into individual tokens
ArrayList<String> words = new ArrayList<String>
while(st.hasMoreElements())
words.add(st.nextToken());
This will give you an array list with the individual words as elements of the list

Related

How do I read a CSV File with JAVA

I have a probem, and I didnt find any solution yet. Following Problem: I have to read a CSV File which has to look like this:
First Name,Second Name,Age,
Lucas,Miller,17,
Bob,Jefferson,55,
Andrew,Washington,31,
The assignment is to read this CSV File with JAVA and display it like this:
First Name: Lucas
Second Name: Miller
Age: 17
The Attribut Names are not always the same, so it also could be:
Street,Number,Postal Code,ID,
Schoolstreet,93,20000,364236492,
("," has to be replaced with ";")
Also the file Adress is not always the same.
I already have the view etc. I only need the MODEL.
Thanks for your help. :))
I already have a FileChooser class in Controller, which returns an URI.
If your CSV file(s) always contains a Header Line which indicates the Table Column Names then it's just a matter of catching this line and splitting it so as to place those column names into a String Array (or collection, or whatever). The length of this array determines the amount of data expected to be available for each record data line. Once you have the Column Names it's gets relatively easy from there.
How you acquire your CSV file path and it's format type is obviously up to you but here is a general concept how to carry out the task at hand:
public static void readCsvToConsole(String csvFilePath, String csvDelimiter) {
String line; // To hold each valid data line.
String[] columnNames = new String[0]; // To hold Header names.
int dataLineCount = 0; // Count the file lines.
StringBuilder sb = new StringBuilder(); // Used to build the output String.
String ls = System.lineSeparator(); // Use System Line Seperator for output.
// 'Try With Resources' to auto-close the reader
try (BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {
while ((line = br.readLine()) != null) {
// Skip Blank Lines (if any).
if (line.trim().equals("")) {
continue;
}
dataLineCount++;
// Deal with the Header Line. Line 1 in most CSV files is the Header Line.
if (dataLineCount == 1) {
/* The Regular Expression used in the String#split()
method handles any delimiter/spacing situation.*/
columnNames = line.split("\\s{0,}" + csvDelimiter + "\\s{0,}");
continue; // Don't process this line anymore. Continue loop.
}
// Split the file data line into its respective columnar slot.
String[] lineParts = line.split("\\s{0,}" + csvDelimiter + "\\s{0,}");
/* Iterate through the Column Names and buld a String
using the column names and its' respective data along
with a line break after each Column/Data line. */
for (int i = 0; i < columnNames.length; i++) {
sb.append(columnNames[i]).append(": ").append(lineParts[i]).append(ls);
}
// Display the data record in Console.
System.out.println(sb.toString());
/* Clear the StringBuilder object to prepare for
a new string creation. */
sb.delete(0, sb.capacity());
}
}
// Trap these Exceptions
catch (FileNotFoundException ex) {
System.err.println(ex.getMessage());
}
catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
With this method you can have 1 to thousands of columns, it doesn't matter (not that you would ever have thousands of data columns in any given record but hey....you never know... lol). And to use this method:
// Read CSV To Console Window.
readCsvToConsole("test.csv", ",");
Here is some code that I recently worked on for an interview that might help: https://github.com/KemarCodes/ms3_csv/blob/master/src/main/java/CSVProcess.java
If you always have 3 attributes, I would read the first line of the csv and set values in an object that has three fields: attribute1, attribute2, and attribute3. I would create another class to hold the three values and read all the lines after, creating a new instance each time and reading them in an array list. To print I would just print the values in the attribute class each time alongside each set of values.

Read Data from text file in Java [duplicate]

This question already has answers here:
How can I read comma separated values from a text file in Java?
(6 answers)
How do I split a string in Java?
(39 answers)
Closed 3 years ago.
I want to load data from a text file as required for part of a basic project. E.g. a text file can look like this:
201,double,70.00,2,own bathroom
202,single,50.00,2,own bathroom
Each piece of data is seperated by a comma, and in this case goes in the order: room number, room type, cost, amount of people, with/without bathroom and there's 5 data for each room and each room information is on a new line.
The code below reads each line individually, but how do I get it to read and store each data/word from the line (without the comma obviously)?
try{
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = reader.readLine();
while (line != null){
System.out.println(line);
line = reader.readLine();
}
reader.close();
} catch(IOException ex){
System.out.println(ex.getMessage());
}
I saw an example using scanner but I heard that it's slower and less efficient.
I also tried using split but I can't figure out how to do it properly.
Thanks.
You can use Files.readAllLines() method and map the data to the dedicated object. Assuming you have such Room object with appropriate constructor you can read and store data like:
List<String> strings = Files.readAllLines(Paths.get("test.txt"));
List<Room> rooms = new ArrayList<>();
for (String line : strings) {
String[] split = line.split(",");
Integer roomNumber = Integer.valueOf(split[0]);
String roomType = split[1];
Double roomCost = Double.valueOf(split[2]);
Integer amount = Integer.valueOf(split[3]);
String bathroom = split[4];
Room r = new Room(roomNumber, roomType, roomCost, amount, bathroom);
rooms.add(r);
}
Then you can get the information for some room for example by room number:
Room room = rooms.stream()
.filter(r -> r.getRoomNumber() == 102)
.findFirst().orElseThrow(NoSuchElementException::new);
Note: If you are using java10 or above you can use orElseThrow() without parameters
You can split the line by the comma , and get an array of values:
try{
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = reader.readLine();
String data[] = null;
while (line != null){
System.out.println(line);
line = reader.readLine();
data = line.split(","); //data will have the values as an array
}
reader.close();
} catch(IOException ex){
System.out.println(ex.getMessage());
}
If I´m not wrong then the described format is the csv format ( https://en.wikipedia.org/wiki/Comma-separated_values)
Here is good overview how you can read csv data:
https://www.baeldung.com/java-csv-file-array

Java Parsing strings [duplicate]

This question already has answers here:
Parse and read data from a text file [duplicate]
(3 answers)
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Effective way to read file and parse each line
(3 answers)
parsing each line in text file java
(7 answers)
Closed 5 years ago.
I got .txt file with nationalities and phone numbers in different formats and all these in single quote symbols, also it contains empty lines (''):
''
'French'
'1-500'
'0345134123'
''
''
'German'
etc
after I parse with the help of readLine() I got arr[0] with each of these lines.
I need to put lines into different arrays: lines with 'nationality' into one array and lines with 'phone numbers' into other.
I tried this
if(!arr[0].equals("''")){
String[] arr1 = arr[0].split("'");
if(!arr1[1].matches("[0-9]+)"){
nations[n] = arr1[1];
n++;
}
else {
phone_numbers[p] = arr1[1];
p++;
}
}
Ofcourse it didn't work
In your question you said that you want
to put lines into different arrays: lines with 'nationality' into one array and lines with 'phone numbers' into other.
public static void main(String[] args) {
try{
File file = new File("path\\to\\yourfile");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
String nationalities = "";
String phones = "";
while((line = br.readLine()) != null){
String[] s = line.split("'");
if(s.length > 0){
if(s[1].matches("[a-zA-Z]+")){
// nationalities
nationalities += (nationalities.isEmpty()) ? s[1] : " " + s[1];
}else{
// line with phone numbers
phones += (phones.isEmpty()) ? s[1] : " " + s[1];
}
}
}
String[] nationArr = nationalities.split(" ");
String[] phoneArr = phones.split(" ");
for(String val : nationArr){
System.out.println(val);
}
System.out.println("------------");
for(String val : phoneArr){
System.out.println(val);
}
}catch(IOException e){
System.out.println("Error");
}
}
I tested with this text file
''
'French'
'1-500'
'0345134123'
''
''
'Japan'
'2-200'
'08078933444'
''
''
''
'Germany'
'2-300'
'00078933444'
''
You will get two array, nationality[nationArr] and line with phone[phoneArr].
Here is the answer.
French
Japan
Germany
------------
1-500
0345134123
2-200
08078933444
2-300
00078933444
I would suggest implementing some sort of system to differentiate between the types of lines. You could put 'n' at the start of the line for nationality, then detect it in your code.... Or if you knew the exact order of these lines e.g. nationality,number,nationality,number... you could easily separate these lines e.g. lineNumber%numOfLineTypes==0 would give you the first type of line...

Convert .csv into a list of arrays

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.

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...
}
}

Categories

Resources