Java Parsing strings [duplicate] - java

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

Related

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

Read a String and an int from text ffile [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
So i want to read a String and an int from a text file and it gets me java.lang.ArrayIndexOutOfBoundsException: 1
public class GetNameAndNumber{
private ArrayList <NameAndNumber> list = new ArrayList <NameAndNumber>();
BufferedReader buf = new BufferedReader(new FileReader("NameAndNumber.txt"));
String linie = buf.readLine();
while(true)
{
linie = buf.readLine();
if(linie == null)
break;
else
{
String split[] = linie.split(" ");
NameAndNumber nan = new NameAndNumber(split[0], Integer.parseInt(split[1]));
list.add(nan);
}
}
}
the "NameAndNumber" class has a String and an int
and this is the text file:
John 1
David 0
Ringo 55
What i don't know is why this one gives me an error, but when i read 2 strings and then an int like
NameAndNumber nan = new NameAndNumber(split[0], split[1], Integer.parseInt(split[2])); - this "NameAndNumber" having two strings and an int
for a text file like
Johnny John 8
Mathew John 0
it gives me no errors and stores the values correctly. why ?
You most likely have a line without 2 strings on it. Maybe a blank line at the end of the file. I would suggest adding code to display each line right after you read it in, for debugging purposes. Then you can see where the bad line is in your input file.
linie = buf.readLine();
System.out.println("line: '" + linie + "'");
You could add additional code to skip lines that don't have two strings.
String split[] = linie.split(" ");
if (split.length < 2) continue; // skip bad input
I am assuming in you first file you have some empty spaces, because I ran your code and it worked fine. I made it fail by adding some empty spaces at the end with the Index out of exception.
One thing you can do it add some checks as follows by doing a trim and checking if the line is empty.
linie = buf.readLine().trim();
if(linie == null || linie.isEmpty())
break;
Try this
for(;;) {
String line = bufferedReader.readLine();
if (line == null) {
break;
}
}

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.

Cannot find correct intersection of two string arrays when there is a comma in the strings [duplicate]

This question already has answers here:
Java: splitting a comma-separated string but ignoring commas in quotes
(12 answers)
Closed 8 months ago.
I have two CSV files: "userfeatures" and "itemfeatures".
Each line in the userfeature is related to specific user. e.g., the first line in the userfeature file is:
005c2e08","Action","nm0000148","dir_ nm0764316","USA"
I need to find the intersection of this line with every line of the 2nd file "itemfeatures". (Actually , I need to repeat this procedure for all the users, i.e, for all lines of "userfeatures").
So, the first comparison will be with the first line of "itemfeatures" that is:
"tt0306047","Comedy,Action","nm0267506,nm0000221,nm0356021","dir_ nm0001878","USA"
The result of intersection should be ["Action", "USA]" but unfortunately, my code only finds ["USA"] as a match. Here is what I've tried so far:
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader userfeatures = new BufferedReader(new FileReader("userFeatureVectorsTest.csv"));
BufferedReader itemfeatures = new BufferedReader(new FileReader("ItemFeatureVectorsTest.csv"));
ArrayList<String> userlines = new ArrayList<>();
ArrayList<String> itemlines = new ArrayList<>();
String Uline = null;
while ((Uline = userfeatures.readLine()) != null) {
for (String Iline = itemfeatures.readLine(); Iline != null; Iline = itemfeatures.readLine()) {
System.out.println(Uline);
System.out.println(Iline);
System.out.println(intersect(Uline, Iline));
System.out.println(union(Uline, Iline));
}
}
userfeatures.close();
itemfeatures.close();
}
static Set<String> intersect(String Uline, String Iline) {
Set<String> result = new HashSet<String>(Arrays.asList(Uline.split(",")));
Set<String> IlineSet = new HashSet<String>(Arrays.asList(Iline.split(",")));
result.retainAll(IlineSet);
return result;
}
static Set<String> union(String Uline, String Iline) {
Set<String> result = new HashSet<String>(Arrays.asList(Uline.split(",")));
Set<String> IlineSet = new HashSet<String>(Arrays.asList(Iline.split(",")));
result.addAll(IlineSet);
return result;
}
}
I think the problem is related to Uline.split(",") and Iline.split(",") because they consider "Comedy,Action" as 1 word and so it cannot find [Action] as intersection of "Comedy,Action" and "Action".
I appreciate it if someone has any idea how to fix this issue.
Try removing the double quotes in both strings .
Because when you split
"tt0306047","Comedy,Action","nm0267506,nm0000221,nm0356021","dir_
nm0001878","USA"
You will get an
Action"
token , which will never match the
"Action"
token.
If you print your line, what does it look like? I think your issue is in reading the file, for example:
"005c2e08","Action","nm0000148","dir_ nm0764316","USA"
split by ',' will result in:
"005c2e08"
"Action"
and so on. While for your second line it will be:
"tt0306047"
"Comedy
Action"
This is why USA is intercepting, but action is not.
Use A csv reader to read in the csv file, then split the attributes of the CSV line by comma. That way you get rid of the quoutes and your code will work
for example, this library is very handy for reading CSV files:
http://opencsv.sourceforge.net/

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

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

Categories

Resources