parsing csv by "," and " " - java

I have file with data format as
userid, friend id, books id, cd id
1, 11 12 14 12, 223 256 333 234 222, 22
2, 78 22, 22 66 11 29, 76 455
3, 123 22 11 234 198 122 881, 34 12 98 64, 22
where I need to use only user id and cd id, But I am unable to separate these fields.
My Java code as below.
BufferedReader in = new BufferedReader(new FileReader("CSV_test.txt"));
BufferedWriter ou =new BufferedWriter(new FileWriter("users.csv"));
String str;
str = in.readLine();
while ((str = in.readLine()) != null) {
String[] ar = str.split(",");
String[] ar1 = ar[1].split("");
ou.write(ar[0]);
ou.write(",");
ou.write(ar1[1]);
ou.newLine(); }
in.close();
ou.close();
}
Is there any issue with this?

Surely you want
String[] ar = str.split(",");
String user = ar[0].trim();
String cd = ar[3].trim();
Note that I'm trimming to remove leading/trailing spaces.
You could split using ", " (note the trailing space) and that would remove the need to further trim(). It does make some assumptions however as to how your fields are separated (commas ? commas-and-spaces?) and perhaps it's worth investigating a CSV library.

No need to reinvent the wheel. While CSV parsing is fairly simple, there are things that might be a little bit complicated (such as escaping the separator in field values). Existing libraries can do this for you, such as OpenCSV or CsvJdbc

Related

Convert text string to octal string

I need to convert a text string to an WinANSIEncoding compliant (Windows code page 1252) octal string (using Java).
"André" should become "101 156 144 162 351" or "\101\156\144\162\351".
I could use a simple string search and replace for each character in the list of allowed characters, but this would probably not be the fastest solutions.
Does anyone know how this should be done?
Thanx
TM
Ps
https://cryptii.com/text-octal
The toOctalString(int i) will help :
Using Streams
String str ="André";
String toOctal = str.chars().boxed().map(Integer::toOctalString)
.collect(Collectors.joining(" "));
System.out.println(toOctal); // 101 156 144 162 351
Workable Demo
Basic loop
String str ="André";
String toOctal ="";
for(char c : str.toCharArray()){
toOctal += Integer.toOctalString(c)+" ";
}
System.out.println(toOctal);

I want to extract strings from a line

Below contents are available in a text file. I want to extract data (Name, age, Working experience, position). How can I do? I tried to extract using java stringtokenizer and split function. But cannot extract data.
Name Age Working Experience Position
John 23 10 Team Leader
Christian Elverdam 27 7 Director
Niels Bye Nielsen 59 16 Composer
Rajkumar Hirani 40 23 Director
Vidhu Vinod Chopra 58 21 Screenplay
Expected ouput:
John |23|10|Team Leader|
Christian Elverdam|27|7 |Director |
Niels Bye Nielsen |59|16|Composer |
Rajkumar Hirani |40|23|Director |
Vidhu Vinod Chopra|58|21|Screenplay |
Don't use StringTokenizer:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
You can use split() if you split on 2 or more spaces: split(" {2,}")
Demo
String input = "Name Age Working Experience Position \n" +
"John 23 10 Team Leader \n" +
"Christian Elverdam 27 7 Director \n" +
"Niels Bye Nielsen 59 16 Composer\n" +
"Rajkumar Hirani 40 23 Director \n" +
"Vidhu Vinod Chopra 58 21 Screenplay\n";
List<String[]> rows = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new StringReader(input))) {
in.readLine(); // skip header line
for (String line; (line = in.readLine()) != null; ) {
rows.add(line.split(" {2,}"));
}
}
for (String[] row : rows)
System.out.println(Arrays.toString(row));
Output
[John, 23, 10, Team Leader]
[Christian Elverdam, 27, 7, Director]
[Niels Bye Nielsen, 59, 16, Composer]
[Rajkumar Hirani, 40, 23, Director]
[Vidhu Vinod Chopra, 58, 21, Screenplay]

JAVA- Splitting string into tokens but fails with error [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I am trying to read from a text file that has 20 lines and supposed to store them into an array and assign them a variable, firstname lastname and grade. Because I have to output them as last name, firstname and grade, I decided to use tokens but somehow I get this error: java.lang.ArrayIndexOutOfBoundsException: 1
public static void main(String[] args) throws IOException {
int numberOfLines = 20;
studentClass[] studentObject = new studentClass[numberOfLines];
readStudentData(studentObject);
}
public static void readStudentData(studentClass[] studentObject)throws {
//create FileReader and BufferedReader to read and store data
FileReader fr = new FileReader("/Volumes/PERS/Data.txt");
BufferedReader br = new BufferedReader (fr);
String line = null;
int i = 0;
//create array to store data for firstname, lastname, and score
while ((line = br.readLine()) != null){
String[] stuArray = line.split(" ");
String stuFName = stuArray[0];
String stuLName = stuArray[1];
int score = Integer.parseInt(stuArray[2]);
studentObject[i] = new studentClass (stuFName, stuLName, score);
i++;
}
br.close();
for(i = 0; i<studentObject.length; i++){
System.out.print(studentObject[i].getStudentFName());
}
}
The error that I get is specifically this line:
String stuLName = stuArray[1];
Here is the text file:
Duckey Donald 85
Goof Goofy 89
Brave Balto 93
Snow Smitn 93
Alice Wonderful 89
Samina Akthar 85
Simba Green 95
Donald Egger 90
Brown Deer 86
Johny Jackson 95
Greg Gupta 75
Samuel Happy 80
Danny Arora 80
Sleepy June 70
Amy Cheng 83
Shelly Malik 95
Chelsea Tomek 95
Angela Clodfelter 95
Allison Nields 95
Lance Norman 88
I think at the last line of your file you have white spaces. make sure last line hast no white space like space or tab.
First, next time you should include the import and output also in your code
for us to easy to fix it, and one more thing, the Class name should be
StudentClass, not studentClass, it have to me different with methods.
Second, I can't test your code without your studentClass ... So I only can guess it:
Consider 1: The text file have one more line (with white space) >> Impossible because String test = " "; test.split(" ")[0] == null;
Consider 2: Your text file has error, to test it, I suggest you to add
System.out.println(line + ".") after while ((line = br.readLine()) != null){
to test it, believe me, you will receive the last line because it's bloged;

str.replaceAll() not matching "\r\n"

I'm trying to convert Unix-style line-endings (LF) in a multi-line string to Windows-style (CR LF).
My plan of attack is to:
replace all CR LF instances with just LF
then replace all LF instances with CR LF
However, this snippet of code isn't matching the "\r\n":
String test = "test\r\ncase";
test.replaceAll("\r\n","\n");
PrintWriter testFile = new PrintWriter("test.txt");
testFile.print(test);
testFile.close();
I've already tried using double/triple/quadruple backslashes. No dice.
I also know that the test string doesn't contain a literal \r\n because it detects them as CR LF when printing to file.
What am I missing here?
You are not gettign the modified String from your code.
String are immutable so you need to save the returned value from replaceAll. There is no method that can change an instance of String
String test = "test\r\ncase";
//Print the character before
for(char c : test.toCharArray()){ System.out.print((int)c + " ");};
System.out.println();
//Save the replace result
test = test.replaceAll("\r\n","\n");
//Print the character after
for(char c : test.toCharArray()){ System.out.print((int)c + " ");};
Show that the test is first not changed then changed
116 101 115 116 13 10 99 97 115 101 //BEFORE
116 101 115 116 10 99 97 115 101 //AFTER

how to put String values into new Line on getting spaces in java

Hii Guys !!!
I have a string with values like 69 17 17 16 2 1 1 26 26 56 56 69 20 19 20 etc .Now As per my need i have to put these values into new String with each values in new line as after each value space is there ..
Any help will be highly appreciated..
Thanx in advance...
String newStr = origStr.replaceAll(" ", " \n");
You should split the String using a specific separator into a List.
Then print out the List using the format required.
This helps when tomorow the String contains digits, decimals, text, etc or they want the text in another format.
String source = "69 17 17 16 2 1 1 26 26 56 56 69 20 19 20";
String[] splitted = source.split(" ");
StringBuilder sb = new StringBuilder();
for (String split : splitted){
sb.append(split).append(System.getProperty("line.separator"));
}
System.out.println(sb.toString());

Categories

Resources