Read String line by line

read string line by line python
read string line by line c#
read string line by line javascript
read string line by line c++
read file line by line java
how to read multiple lines from a file in java
java read file line by line scanner
read file line by line java 11

Given a string that isn't too long, what is the best way to read it line by line?

I know you can do:

BufferedReader reader = new BufferedReader(new StringReader(<string>));
reader.readLine();

Another way would be to take the substring on the eol:

final String eol = System.getProperty("line.separator");
output = output.substring(output.indexOf(eol + 1));

Any other maybe simpler ways of doing it? I have no problems with the above approaches, just interested to know if any of you know something that may look simpler and more efficient?

You can also use the split method of String:

String[] lines = myString.split(System.getProperty("line.separator"));

This gives you all lines in a handy array.

I don't know about the performance of split. It uses regular expressions.

How to read a String line by line, In such a case you can easily use StringReader class. The follwoing example shows how to print the first character of each line of a textarea content: String str;​  It’s easy to read a string one line at a time. Here is a console program that demonstrates how: using System; using System.IO; namespace CSharp411 { class Program { static void Main( string[] args ) { string text = "HellonGoodbye, worldnnDon't have a cow"; using (StringReader reader = new StringReader( text )) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine

There is also Scanner. You can use it just like the BufferedReader:

Scanner scanner = new Scanner(myString);
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  // process the line
}
scanner.close();

I think that this is a bit cleaner approach that both of the suggested ones.

Java read file line by line, Java Read File line by line using BufferedReader​​ We can use java. io. BufferedReader readLine() method to read file line by line to String. This method returns null when end of file is reached. Reads a line of characters from the current string and returns the data as a string. public: override System::String ^ ReadLine (); C#. public override string ReadLine (); override this.ReadLine : unit -> string.

Since I was especially interested in the efficiency angle, I created a little test class (below). Outcome for 5,000,000 lines:

Comparing line breaking performance of different solutions
Testing 5000000 lines
Split (all): 14665 ms
Split (CR only): 3752 ms
Scanner: 10005
Reader: 2060

As usual, exact times may vary, but the ratio holds true however often I've run it.

Conclusion: the "simpler" and "more efficient" requirements of the OP can't be satisfied simultaneously, the split solution (in either incarnation) is simpler, but the Reader implementation beats the others hands down.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Test class for splitting a string into lines at linebreaks
 */
public class LineBreakTest {
    /** Main method: pass in desired line count as first parameter (default = 10000). */
    public static void main(String[] args) {
        int lineCount = args.length == 0 ? 10000 : Integer.parseInt(args[0]);
        System.out.println("Comparing line breaking performance of different solutions");
        System.out.printf("Testing %d lines%n", lineCount);
        String text = createText(lineCount);
        testSplitAllPlatforms(text);
        testSplitWindowsOnly(text);
        testScanner(text);
        testReader(text);
    }

    private static void testSplitAllPlatforms(String text) {
        long start = System.currentTimeMillis();
        text.split("\n\r|\r");
        System.out.printf("Split (regexp): %d%n", System.currentTimeMillis() - start);
    }

    private static void testSplitWindowsOnly(String text) {
        long start = System.currentTimeMillis();
        text.split("\n");
        System.out.printf("Split (CR only): %d%n", System.currentTimeMillis() - start);
    }

    private static void testScanner(String text) {
        long start = System.currentTimeMillis();
        List<String> result = new ArrayList<>();
        try (Scanner scanner = new Scanner(text)) {
            while (scanner.hasNextLine()) {
                result.add(scanner.nextLine());
            }
        }
        System.out.printf("Scanner: %d%n", System.currentTimeMillis() - start);
    }

    private static void testReader(String text) {
        long start = System.currentTimeMillis();
        List<String> result = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new StringReader(text))) {
            String line = reader.readLine();
            while (line != null) {
                result.add(line);
                line = reader.readLine();
            }
        } catch (IOException exc) {
            // quit
        }
        System.out.printf("Reader: %d%n", System.currentTimeMillis() - start);
    }

    private static String createText(int lineCount) {
        StringBuilder result = new StringBuilder();
        StringBuilder lineBuilder = new StringBuilder();
        for (int i = 0; i < 20; i++) {
            lineBuilder.append("word ");
        }
        String line = lineBuilder.toString();
        for (int i = 0; i < lineCount; i++) {
            result.append(line);
            result.append("\n");
        }
        return result.toString();
    }
}

Reading a File Line by Line in Java, hasNextLine()) { String line = scanner.nextLine(); // process the line }. The hasNextLine() method returns true if there is another line in the input of this scanner,  To read a text file line by line using C# programming, follow these steps. Import System.IO for function to read file contents. Import System.Text to access Encoding.UTF8. Use FileStream to open the text file in Read mode.

Using Apache Commons IOUtils you can do this nicely via

List<String> lines = IOUtils.readLines(new StringReader(string));

It's not doing anything clever, but it's nice and compact. It'll handle streams as well, and you can get a LineIterator too if you prefer.

Read a file line by line in Python, How do I read a text file line by line? Example 1: Read Text File Line by Line – readline() Following are the steps to read text line by line using readline() function. Read file in text mode. Create an infinite Loop. During each iteration of the loop, read the line from the file using readline(). If the line is not empty, you have the current line. Else, there are no more lines in the file, and we can break the loop.

Solution using Java 8 features such as Stream API and Method references

new BufferedReader(new StringReader(myString))
        .lines().forEach(System.out::println);

or

public void someMethod(String myLongString) {

    new BufferedReader(new StringReader(myLongString))
            .lines().forEach(this::parseString);
}

private void parseString(String data) {
    //do something
}

Adding a Newline Character to a String in Java, How do you read a string line by line in Python? readlines () is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines. We can iterate over the list and strip the newline ' ' character using strip () function.

How to read file line by line in Java, How do you read a specific line from a text file in Java? Being able to read a file line by line gives us the ability to seek only the relevant information and stop the search once we have found what we're looking for. It also allows us to break up the data into logical pieces, like if the file was CSV-formatted. There are a few different options to choose from when you need to read a file line by line.

StringReader.ReadLine Method (System.IO), is as simple as including “\n” or “\r” or “\r\n” at the end of our string. Java Read File line by line using BufferedReader We can use java.io.BufferedReader readLine () method to read file line by line to String. This method returns null when end of file is reached. Below is a simple program showing example for java read file line by line using BufferedReader.

Java 11 String.lines() - Stream of lines, txt is read by FileReader class. The readLine() method of BufferedReader class reads file line by line, and each line appended to StringBuffer, followed by a  2 minutes to read +6; In this article. This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class. Each text line is stored into the string line and displayed on the screen. Example int counter = 0; string line; // Read the file and display it line by line.

Comments
  • Well your requirement said "read it line by line", which implies you don't need all the lines in memory at one time, so I would stick with the BufferedReader or Scanner approach, whichever you feel more comfortable with ( don't know which is more efficient). This way your memory requirements are less. It will also allow you to "scale up" the application to use larger strings by potentially reading data from a file in the future.
  • And hope the line separator doesn't have regex characters in it. :)
  • "line.separator" is not reliable anyway. Just because the code is running on (e.g.) Unix, what's to stop the file from having Windows-style "\r\n" line separators? BufferedReader.readLine() and Scanner.nextLine() always check for all three styles of separator.
  • I know this comment is really old, but ... The question doesn't mention files at all. Assuming the String was not read from a file, this approach is probably safe.
  • @Jolta This is not safe even for manually constructed Strings, if you're on windows and constructed your String with '\n' and then split on line.separator you get no lines.
  • Huh? If I create a string on my linux box using line.separator and someone else reads it on windows using line.separator, it's still humped. That's not incompetent coders from doing stupid things, it's just how things (don't always) work.
  • I don't think it's a fair comparison though - String.split relies on the entire input being read into memory, which isn't always feasible (e.g. for large files).
  • The input has to reside in memory, given that the input is String. The memory overhead is the array. Also, the resulting Strings reuse the same back-end character array.
  • Beware Scanner can produce wrong results if you scan an UTF-8 file with Unicode characters and don't specify the encoding in Scanner.It might interpret a different character as end of line. In Windows it uses its default encoding.
  • As of Java8, the BufferedReader has a lines() function returning a Stream<String> of the lines, which you can collect into a list if you wish, or process the stream.
  • One drawback of this approach is that IOUtils.readlines(Reader) throws an IOException. Even though this will probably never happen with a StringReader, you'll have to catch or declare it.
  • There is a slight typo, it should be: List lines = IOUtils.readLines(new StringReader(string));
  • Didn't even knew that ! Thank's a lot .
  • Hardcoding the representation of newline makes the solution platform-dependent.