Read Data from text file in Java [duplicate] - java

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

Related

how to print string array onto file? [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Convert array of strings into a string in Java
(14 answers)
Closed last month.
I have a string input file and I put the strings into arrays. I only want to print the last element of each string array onto my console and onto a output array. When I run my code, I get the last element of each string array onto my console, but see this on my output file:
[Ljava.lang.String;#51d5f7fd
How can I print the actual string array to show up on output file and not its string representation? I'll show you my code so you get a better understanding of what I'm trying to do:
try {
br = new BufferedReader(new FileReader("C:\\rd\\bubble.txt"));
//first, create new file object
File file = new File("C:\\rd\\bubble_out.txt");
if(file.exists()) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
String line = "";
while((line = br.readLine()) != null) { //while the line is not equal to null
String[] arr = line.split("\\s+"); //split at whitespace
System.out.println(arr[arr.length - 1]);
pw.println(arr);
pw.close();
}
}
catch(IOException x)
{
System.out.println("File not found");
}
}
}
}
}
I've tried using Array.toString() method, but I'm not sure how to implement it into my code correctly. I'm currently trying to do that, but if there's an easier way to do this, please let me know.
Use Arrays.toString to get a readable String representation of the array.
Don't close the PrintWriter inside the loop as you have not finished writing all output. You can use try with resources to avoid having to explicitly close it.
try (PrintWriter pw = new PrintWriter(file)) {
while((line = br.readLine()) != null) {
String[] arr = line.split("\\s+");
System.out.println(arr[arr.length - 1]);
pw.println(Arrays.toString(arr));
}
}

skipping lines while reading from csv file in java [duplicate]

This question already has answers here:
BufferedReader is skipping every other line when reading my file in java
(3 answers)
Closed 3 years ago.
private static List<Book> readDataFromCSV(String fileName) {
List<Book> books = new ArrayList<>();
Path pathToFile = Paths.get(fileName);
// create an instance of BufferedReader
// using try with resource, Java 7 feature to close resources
try (BufferedReader br = Files.newBufferedReader(pathToFile,
StandardCharsets.US_ASCII)) {
// read the first line from the text file
String line = br.readLine();
// loop until all lines are read
while ((line = br.readLine())!= null) {
// use string.split to load a string array with the values from
// each line of
// the file, using a comma as the delimiter
String[] attributes = line.split("\\|");
Book book = createBook(attributes);
// adding book into ArrayList
books.add(book);
// read next line before looping
// if end of file reached, line would be null
line = br.readLine();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return books;
}
private static Book createBook(String[] metadata) {
String name = metadata[0];
String author = metadata[1]; // create and return book of this metadata
return new Book(name, price, author);
}
The above code skips every second line from text file (a csv file).
It gives data of alternate lines and it uses Java 7 syntax.
Please provide some suggestion what is wrong or how to improve it.
Remove the br.readLine() inside the while condition i.e.
// read the first line from the text file
String line = br.readLine();
// loop until all lines are read
while (line != null)
{
...
// read next line before looping
// if end of file reached, line would be null
line = br.readLine();
}
You have called the br.readLine() function twice in the loop.
One is in the condition:
while((line = br.readLine()) != null)
and the second one is at end of the loop.
So the loop is actually reading a line at the end, and then reading the next line at the beginning without processing it. To avoid this, you can remove the br.readLine at the end of the loop.
while ((line = br.readLine())!= null)
{
// use string.split to load a string array with the values from
// each line of
// the file, using a comma as the delimiter
String[] attributes = line.split("\\|");
Book book = createBook(attributes);
// adding book into ArrayList
books.add(book);
}
If you did not get it, the condition:
while((line = br.readLine()) != null)
is actually doing the following:
storing the returned value of br.readLine() in the variable line,
and then checking the condition. Therefore, you do not need to call it again in the loop.

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

Java - Most efficient way to read in a CSV file with various data types

I'm attempting to read in a CSV file with various data types.
A row of the sheet would be like below:
Single, Monthly, Accelerated, John, Smith, 08/15/1951, Yes
I then need to assign each field to a variable name, preform some calculations, print an output and then move onto the next line in the excel sheet
Up until now, I've been using the below
ArrayList<String> lines = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
But this creates an array with each slot containing a long string with the text (including comma) of the corresponding excel row.
This seems inefficient and impractical as i then have to traverse each slot/string to extract the values.
Once I have the methodology, I wont have any issue writing the code but i don't know the best way to go about it
Is it better to read each cell separately and assign to a variable ?
Or is it better to read in a file once and traverse it afterwards?
Perhaps there is a more efficient way to do this task
Edit : I also though of attempting to read in the entire CSV file as a 2D array, but the different data types could be an issue..?
You can try something similar to this. Use StringTokenizer to split the line by comma and add those elements to another List as strings in each iteration.
ArrayList<ArrayList<String>> lines = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = reader.readLine()) != null) {
ArrayList<String> tokens = new ArrayList<>();
StringTokenizer st = new StringTokenizer(line, ",");
while (st2.hasMoreElements()) {
tokens.add(st2.nextElement());
}
lines.add(tokens);
}
}
Now you can use proper casts to convert them to types you want. For example, to get the date,
DateFormat format = new SimpleDateFormat("mm/dd/yyyy", Locale.ENGLISH);
String dateString = lines.get(0).get(5);
Date date = format.parse(dateString);
You don't need to store the lines. Instead create a class that represents each row and add them to a list.
Something like :
class MyData
{
String status;
String salary;
String accelerated;
String firstName;
String lastName;
String date;
String trueOrFalse;
}
You could keep them without any access qualifier or make them private and add getter/setters.
In your file reader, split the line using the separator used in csv which is by default a comma ( , )
ArrayList<MyData> datas = new ArrayList<MyData>();
while ((line = reader.readLine()) != null) {
String[] columns = line.split( "," );
MyData data = new MyData();
data.status = columns[0];
data.salary = columns[1];
.
.
data.trueOrFalse = columns[6];
datas.add( data );
}
OR
If you want to just perform some calculations and print, you don't need a separate class or even ArrayList<String> lines.
Just do :
while ((line = reader.readLine()) != null) {
String[] columns = line.split( "," );
// Perform calculations with columns
// Print.
}
No need to store information if that is the case.

Reading files with use of Delimiter in Java [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 5 years ago.
I am trying to read text file with 3 lines:
10
PA/123#PV/573#Au/927#DT/948#HY/719#ZR/741#bT/467#LR/499#Xk/853#kD/976#
15.23#25.0#17.82#95.99#23.65#156.99#72.85#62.99#112.0#55.99#
So far in my main method I have:
`String fileName = "productData.txt";
String line = null;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
catch(FileNotFoundException e) {
System.out.println(e);
}
catch(IOException e) {
e.printStackTrace();
}`
But Im not sure how I would go on with using the String DELIMITER = "#";
In the text file Line 1: is applied to number of types of product, Line 2: are product codes separated by #, and in Line 3: Price per unit of the corresponding products separated by #.
So Im looking for kind of format PA/123 Costs 15.23. How would I do that?
You can you line.split('#'); to get an array of Strings. This array contains your 10 elements.
Then you have two arrays of size 10. So firstArray[0] contains the name of the first product and secondArray[0] contains the price of it.

Categories

Resources