2

a.txt :

1,2,3
1,2,6
2,4,5

Reading and splitting

String wynik = readFileAsString("a.txt");
String[] wyniki = wynik.split("");

I can't seem to find a way to split String out after newLines that are in file, and not specified like this (this is what I found on all other examples on stackoverflow):

1,2,3\n1,2,6\n2,4,5\n

My readFileAsString works correctly, and it actually reads it that way (without splitting):

1,2,31,2,62,4,5

I know I could add something to my file, to make it split by it, eg

1,2,3t
...

But I also need that file to be clear and without any unnecessary symbols.

Entire thing looks like this:

public static String readFileAsString(String file) {
    String line, results = "";
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        // readLine() zwraca nulla na koncu pliku, stad zabezpieczenie
        while ((line = reader.readLine()) != null) {
            results += line;
        }
        reader.close();
        // return results;
    } catch (IOException e) {
        System.err.println("Error");
    }
    return results;
}

    public static void main(String args[]) {

        String wynik = readFileAsString("a.txt");
        System.out.println(wynik);
        String[] wyniki = wynik.split("[\\r\\n]+");

        ArrayList<Trojka> wynikArrList = new ArrayList<Trojka>();

        for (int i = 0; i < wyniki.length; i++) {
            String[] temp1 = wyniki[i].split(",");
            int m = 0;
            int n = 0;
            int t = 0;
            try {
                m = Integer.parseInt(temp1[0]);
            } catch (Exception e) {
            }
            try {
                n = Integer.parseInt(temp1[1]);
            } catch (Exception e) {
            }
            try {
                t = Integer.parseInt(temp1[2]);
            } catch (Exception e) {
            }

            Trojka temp = new Trojka(m, n, t);

            boolean newRecord = true;
            for (Trojka a : wynikArrList) {
                if (a.getM() == temp.getM() && a.getN() == temp.getN()) {
                    a.addT((int) temp.getT());
                    newRecord = false;
                    break;
                }
            }
            if (newRecord) {
                wynikArrList.add(temp);
            }
        }

        wynik = "";

        for (Trojka a : wynikArrList) {
            wynik += a.getM() + "," + a.getN() + "," + a.getT() + "\n";
        }

        System.out.println(wynik);  

    }
}
Kamil Gosciminski
  • 14,490
  • 4
  • 39
  • 60

3 Answers3

2

If you want to split a string by newlines then try this regex:

String[] out2 = out.split("[\\r\\n]+");

Update: code for readFileAsString should be like this:

public static String readFileAsString(String file) {
   return new Scanner(new File(file)).useDelimiter("\\Z").next()'
}

Update 2:

public static String readFileAsString(List<String> Lines, String file) {
    String line, results = "";
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        // readLine() zwraca nulla na koncu pliku, stad zabezpieczenie
        while ((line = reader.readLine()) != null) {
            results += line;
            lines.add(line);
        }
        reader.close();
        // return results;
    } catch (IOException e) {
        System.err.println("Error");
    }
    return results;
}

Now call it as:

ArrayList<Trojka> wynikArrList = new ArrayList<Trojka>();
String wynik = readFileAsString(wynikArrList, "a.txt");
anubhava
  • 664,788
  • 59
  • 469
  • 547
  • It's not working as I wanted it to. The output after that split is : ``1,2,31,2,62,4,5 (newline here) 1,2,31.0`` – Kamil Gosciminski Nov 30 '13 at 10:16
  • 1
    @nobodynoone: How are you printing resulting array after split? – anubhava Nov 30 '13 at 10:18
  • @anubhava: read once again please, you can see what **a.txt** contains :) – Kamil Gosciminski Nov 30 '13 at 10:19
  • Ok, I might need to update my question in order for you to get a better understanding about my printing. **It's done**. – Kamil Gosciminski Nov 30 '13 at 10:21
  • @nobodynoone: Thanks for your edit, can you also post your code for `readFileAsString` method. – anubhava Nov 30 '13 at 10:25
  • ok your `readFileAsString` appears to be a problem. Let me give you some code for that. – anubhava Nov 30 '13 at 10:27
  • The method you've written doesn't work. Even though I added handling FileNotFound exception, it just contains errors. And what's wrong with the previous one? It reads the file without new lines. – Kamil Gosciminski Nov 30 '13 at 10:32
  • In your previous code you are **stripping out** all the new lines. You will not need split again if you are using old code. You can directly store each line of the file in an ArrayList. Got it? – anubhava Nov 30 '13 at 10:34
  • The problem has been fixed. I just had to add ``\n`` to variable ``results`` while adding lines to that String. That makes the previous file (the one I'm reading from) still look clear, and the output is what I was looking for. ``results += line + "\n";`` **Your regex + that modification solved the problem. Could you please tell me what does this regex stand for? First time I see thing like this :)** – Kamil Gosciminski Nov 30 '13 at 10:34
  • @nobodynoone: I also made another update where I show how you can read input file in a String as well store those individual lines in an ArrayList. – anubhava Nov 30 '13 at 10:38
  • 1
    This regex: `[\\r\\n]+` will match ` or more of `\r` OR `\n` characters that form newlines on various systems. `[ and ]` is called a character class where you can give a list of characters/symbols for matching. – anubhava Nov 30 '13 at 10:40
  • 1
    Thanks for your effort. Solved. – Kamil Gosciminski Nov 30 '13 at 10:44
  • One more thing, what ``+`` does here? – Kamil Gosciminski Nov 30 '13 at 10:55
  • 1
    `+` in regex is for 1 or more matches. See this site for good info on regex: http://regular-expressions.info – anubhava Nov 30 '13 at 17:54
1

Be aware of the fact that a "new line" is represented by different characters, depending on the context. A save approach is to use split("\\R") (available in Java8+).

Example:

final String[] a = "one\ntwo\r\nthree\rfour\n".split("\\R");
assertArrayEquals(new String[]{"one", "two", "three", "four"}, a);

Also see https://stackoverflow.com/a/31060125/868941

Community
  • 1
  • 1
rmuller
  • 10,058
  • 3
  • 50
  • 80
0

You are trying to split your string with "", wich is the empty string. If you want to split it with by newline, use "\n" instead. But, since we do not see how you read the file (the read, you probably a returning a concatenated string fromreadFileAsString`, it is hard to tell where it is going wrong.

Salandur
  • 6,283
  • 2
  • 20
  • 23
  • As you can see, the reason i have ``""`` is that I had no idea how to make it work. I do not have ``"\n"`` anywhere in my file. Now reading method is added. – Kamil Gosciminski Nov 30 '13 at 10:27