Reputation: 3557
I am writing code to split lines in java but it doesn't work properly.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.lang.*;
public class mainprogram {
public static void main(String [] args ) throws FileNotFoundException, IOException
{
//creating object for purpose of writing into file
writFile ObjectwritFile = new writFile();
//creating object for purpose of reading from file
loadFile ObjectloadFile = new loadFile();
//this will be used for storing text into from file
String text="";
//text = ObjectloadFile.loadFile("C://names.txt");
System.out.println(text);
ObjectwritFile.writeFile("C://testfile.txt",text);
//these regexp didn't work
//String regexp = "[\\r\\n]+";
//String regexp = "[\\s,;\\n\\t]+";
String regexp = "[\\n]+";
//this one didn't work
//String[] lines = text.split(regexp);
String[] lines = text.split(System.getProperty("line.separator"));
for(int i=0; i<lines.length; i++){
System.out.println("Line "+i+": "+lines[i]);
ObjectwritFile.writeFile("C://testfilelines.txt","Line "+i+": "+lines[i]);
}
}
}
The text is in this format.
John, Smith, 4 ,5 ,6
Adams, Olsen, 7,8, 3
Steve, Tomphson , 4,5 9
Jake, Oliver, 9,8,9
Once I separate text by lines I have to sort it by alphabet and but numbers into a file with same text format.
Upvotes: 2
Views: 4079
Reputation: 425348
Try this:
String[] lines = text.split("\n+");
Note that "\n"
is not a special regex character, so it doesn't need escaping. The regex "\\n"
(in java) is the literal "n"
Upvotes: 2
Reputation: 128919
I don't fully understand what you're trying to do, but if your input text is consistently in the format: String,String,int,int,int
, then this groovy code will read the lines, sort them by the final three numbers in ascending order, and print them out:
def lines = new File('textSort.txt').readLines()
lines.sort{ it.split(',')[4].trim() }
lines.sort{ it.split(',')[3].trim() }
lines.sort{ it.split(',')[2].trim() }
println lines.join('\n')
It's a little hacky sorting three times, but it gets the job done and will work fine unless you have a large dataset. The Java code for it would be correspondingly much larger.
Upvotes: 1
Reputation: 26733
Why bother doing everything by hand? Just use one of the available CSV libraries, such as Super CSV.
Upvotes: 1
Reputation: 46428
String regexp = "[\\n]+";
//this one didn't work
//String[] lines = text.split(regexp);
you don't need to escape \n
with an extra backslash \\n
as \n
is a valid escape sequence.
String regexp ="[\n]+"; //will work fine
Upvotes: 0