Splitting String in case of a new line [duplicate] - java

This question already has answers here:
Split Java String by New Line
(21 answers)
Closed 6 years ago.
I have a method in java which returns the updated lines of a flat file as a "String". I am receiving the String as a bunch of lines, what i want to do is to separate the String line by line. How can i do that in java?????

I will suggest make use of system property line.separator for this splitting to make your code work on any platform eg: *nix, Windows, Mac etc. Consider code like this:
String str = "line1\nline2\nline3";
String eol = System.getProperty("line.separator");
System.out.printf("After Split - %s%n", Arrays.toString(str.split(eol)));

String lines[] = fileString.split("\\r?\\n"); //should handle unix or win newlines

I am not sure about with single string separator .
but i roughly write a method that may be relevant to you .
public void splitter (DocumentEvent e) {
String split[], docStr = null;
Document textAreaDoc = (Document)e.getDocument();
try {
docStr = textAreaDoc.getText(textAreaDoc.getStartPosition().getOffset(), textAreaDoc.getEndPosition().getOffset());
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
split = docStr.split("\\n");
}

Related

how to trim a string twice and getting different info? [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 6 years ago.
I'm working an project where the program is supposed to analyze other project, the other projects are located in a specisfic directory. The projects are named under a standard similar to the following:
Projectname-version-downloadingDate example:
ElasticSearch-1.0-20160417
right now the program can return the whole project name as one string and save it to CSV file, using the following methods:
private String projectName;
public void setProjectName(String projectName){
this.projectName = projectName;
}
public String getProjectName(){
return projectName;
}
and here is the method call for writing the name of the project:
private void writeReport() {
BufferedWriter out = null;
try {
File file = new File("out.csv");
boolean exists = file.exists();
FileWriter fstream = new FileWriter(file, exists /*=append*/);
out = new BufferedWriter(fstream);
if (!exists) {
out.write("File Name;");
out.write(System.getProperty("line.separator"));
}
out.write(String.valueOf(newFiles.getProjectName()) + ";"); //method call
out.write(System.getProperty("line.separator"));
// }
//Close the output stream
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
// return;
}
}
now my question is how can I split the name of the project into three parts and write each one separated in the CSV file?
the project name, the version and the download date? meaning that it should take the project name from the substring located before the first "-" and the version after the first "-" and finally the date after the second "-"?
any tips how to do that?
thanks
Use the string.split method.
String string = "ElasticSearch-1.0-20160417";
String[] parts = string.split("-");
String projectName = parts[0]; // ElasticSearch
String versionNumber= parts[1]; // 1.0
String downloadDate= parts[2]; // 20160417

Java split CSV with two patterns [duplicate]

This question already has answers here:
CSV API for Java [closed]
(10 answers)
Closed 7 years ago.
I have this CSV with this format, I need to split in 16 Parts, according with the text's:
"MY TEXT","EVER, OK",,,,,,,,,,"The, CARLO","DO","ALFA","OME, GA",,
I have this way, but when appear case's with commas inside "OME, GA" doesn't work.
String[] lineToMap = line.split(",");
How I can control this cases?
Solution
I discovered this library: OPEN CSV, in my Test's work very well, but I have a problem with the codification (strange symbols like � instead ü), with characters like ü, ö, etc.. I'm using languages like German and French. I was testing with UTF-8 but didn't work, Any idea to fix this?
CSVReader reader=new CSVReader(new InputStreamReader(new FileInputStream("data/test.csv"), "UTF-8"),
',', '"', 0);
//Read CSV line by line and use the string array as you want
String[] nextLine;
try {
while ((nextLine = reader.readNext()) != null) {
if (nextLine != null) {
for (String element : nextLine) {
System.out.println(element);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Trying splitting on "," instead and handle the edge cases at the beginning and end of the arrays by hand.

Java - Regex error when using "\\" as a delimeter [duplicate]

This question already has answers here:
Why String.replaceAll() in java requires 4 slashes "\\\\" in regex to actually replace "\"?
(6 answers)
Closed 7 years ago.
The following code is from a method in a class that I am making to modify a list of file directories in a program folder. However I am trying to use "\" as a delimiter for a scanner as I only need the start of the directory "S:\" and the last part which is just name of a sub folder. So for example it looks like this:
F:\Data\Subfolder\Another
The code complies but when I run the method i get this following run time error:
java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
And was just wondering if anyone knows what it means and how I can stop it from happening. Is it because of using the \ for a delimeter?
Note: newFolder class is a nested class
public void scanFiles() throws IOException{
try
{
System.out.println("Sage 2015 is Installed on this machine");
File companyFile = new File(sageFolders[8] + "\\COMPANY");
Scanner input = new Scanner(new BufferedReader(new FileReader(companyFile)));
input.useDelimiter("\\");
while(input.hasNextLine())
{
if(line.contains("F"))
{
String drive = input.next();
String dataFolder = input.next();
String sageFolder = input.next();
String clientFolder = input.next();
newFolders.add(new newFolder(drive, clientFolder));
}
}
//Close the Readers
fileReader.close();
bufferedReader.close();
//fileWriter = new FileWriter(companyFile);
//bufferedWriter = new BufferedWriter(fileWriter);
//Write back to file
//fileWriter.flush();
//bufferedWriter.close();
}
catch(FileNotFoundException e)
{
System.out.println("File not Found: Moving onto next Version");
}
}
class newFolder
{
private String driveLetter;
private String clientFolder;
public newFolder(String driveLetter, String clientFolder)
{
this.driveLetter = driveLetter;
this.clientFolder = clientFolder;
}
}
Since \ is regex special character and also special in Java, you have to escape your java backslash with \\ and also your regex backslash with \\, hence... you have four backslashes \\\\
You have to use:
input.useDelimiter("\\\\");

Find a String and return the words after it [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have this method which receive as parameters pdfText(which is a String containing text from a pdf file after parsing) and fileName which is the file where i want to write that text
But now I need to find the word "Keywords" in this text and extract only the words after it,which are in the same line(until the newline character).
For example I have one text which contains somewhere the following line
Title:Something.
"Keywords : Computers, Robots, Course"
Tags:tag1,tag2,tag3.
And the result should be the following list ["Computers","Robots", "Course"].
Solved Question
So I've searched how to solve my question..here is a solution,not very smart but it works:
//index of first appearence of the word
int index = pdfText.indexOf("Keywords");
//string from that to the end
String subStr = pdfText.substring(index);
//index of first appearence of the new line in the new string
int index1 = subStr.indexOf("\n");
//the string we need
String theString = subStr.substring(9,index1);
System.out.println(theString);
//write in the file..use true as parameter for appending text,not overwrite it
FileWriter pw = new FileWriter(fileName,true);
pw.write(theString);
pw.close();
Honestly, this question is too situation specific. Regardless :)
Writing to file
String pdfText = "pdfText";
String fileLocation = "fileLocation";
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileLocation), "utf-8"));
writer.write(pdfText); // String you want to write (i.e. pdfText)
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {writer.close();} catch (Exception ex) { ex.printStackTrace(); }
}
It's always a good idea to specify the encoding type. ("utf-8"). It might not matter for your assignment though. You might also need to append to the file, and not re-write it completely, in which case, you should use a different constructor for the FileOutputStream, new FileOutputStream(getFileLocation(), true) . As for the many try/catch blocks, don't follow my example. It's how I manage to close my resource, as eclipse recommends haha.
Parsing the String
If you have a line such as "Keywords : Computers, Robots, Course",
String str = "Keywords : Computers, Robots, Course";
String[] array = str.substring(indexOf(':') + 1).split(",");
//this array = ["Computers", "Robots", "Course"]
Now you have an array which you can loop through and write/print out however you'd like.
You could use regex to extract the words after the word "Keyword:" like this :
String regex = ".*Keywords\\s*:(.*)\\n.*";
String extractedLine = yourText.replaceAll( regex, "$1" );
System.out.println( extractedLine );

Parse string in Java [duplicate]

This question already has answers here:
string parsing in java
(4 answers)
Closed 7 years ago.
I have a string in below format
// JCSDL_MASTER b04591342ee71a2baa468d9d2a340ec8 AND
// JCSDL_VERSION 1.0
// JCSDL_START 0980a5f2ef935c4ed153bf975879eac0 twitter.text,contains_any,27-52
twitter.text contains_any "obama, santorum, gingrich, romney, ronpaul, ron paul"
// JCSDL_END
AND
// JCSDL_START f7c18a6fedd90c6b4d77acc14a3a8e5c interaction.type,in,21-29
interaction.type in "twitter,facebook,digg,youtube"
// JCSDL_END
// JCSDL_MASTER_END
I suppose it include newline character at the end, i need to just get only those line which is not being started by // how to get only those lines?
Pretty simply, just split up the string into individual lines (note: \n is an escape character for a line break), then only use each line if it does not start with //
String[] lines = string.split("\\n");
for (String line : lines)
{
if (!line.startsWith("//"))
{
//use the line and do your thing
}
}
Use Scanner.nextLine() to read each line and then Ignore the ones which starts with // like following:
String str = "hi \n//this is kuleep\nthis is a test class";
Scanner sc = new Scanner(str);
while (sc.hasNextLine()) {
String line = sc.nextLine();
if(!line.startsWith("//"))
{
System.out.println(line);
}
}

Categories