-2

enter image description here

enter image description here

enter image description here

I want to split the file in the picture and i can't because of the lines...The output i get is all together.What is the right command in regex to split even if there is a new line ?

Saif Ahmad
  • 1,118
  • 1
  • 8
  • 24
  • 2
    Please post the code and file content as text instead of picture. [edit] the question accordingly. See [Discourage screenshots of code and/or errors](https://meta.stackoverflow.com/q/303812/4391450) – AxelH May 02 '18 at 09:55

2 Answers2

0

This should do:

protasi[] = string.split("\\r?\\n");

split("\n") won't work because you need to provide a back-slash for \n which becomes \\n. I'd also added \\r which is what we should use for newline/carriage return.

Shanu Gupta
  • 3,699
  • 2
  • 19
  • 29
0

You are reading the file using a Scanner to get each line.

 while(sc.hasNextLine())

You append the StringBuffer with each line (without a separators).

sb.append(sc.nextLine())

So at that point, a file with :

foo
bar

Would give a StringBuffer with

sb.toString(); //foobar

So there is not line separator left... Instead, do that with the Scanner.

while(sc.hasNextLine()){
    String s = sc.nextLine();
    System.out.println(s):
    sb.append(s);
}

Last thing, please close every Scanner you open with sc.close() when you are done with them (that's a good practice to have).

EDIT:

If you want to keep that logic, simply append with a line separator after each lines:

while(sc.hasNextLine()){
    sb.append(sc.nextLine()).append("\n");
}

That way, you will always have a line separator and the split will work

Quick example of what this would look like :

StringBuffer sb = new StringBuffer();
sb.append("foo").append("\n")
  .append("bar").append("\n"); //fake "file reading"

String[] result = sb.toString().split("\n");
for(String s : result){
    System.out.println(s);
}

foo
bar

AxelH
  • 14,325
  • 2
  • 25
  • 55