Ken
Ken

Reputation: 3

Java : read file and stop at new line context

For example, given a txt file:

words
123
words:123
words:324

words
123
words:123
words:324

Is it possible to do this?

FileReader fr = new FileReader(//the txt file mentioned above); 
Scanner s = new Scanner(fr).useDelimiter(//something which equal to the empty string after each venue);
while (s.hasNext()){
        String paragraph = s.next();
        break;
    }

Is it possible to read just up to a blank line? So paragraph would be equal to :

words
123
words:123
words:324

Upvotes: 0

Views: 1797

Answers (2)

Kangkan
Kangkan

Reputation: 127

See if this helps

public static void main(String[] args) throws FileNotFoundException  {

File your_file = new File("D:/text_document.txt"); //your text file
Scanner sc = new Scanner(your_file); // initialize your 
//scanner with text file
String s ="";
while(sc.hasNextLine()){
    s =s+sc.nextLine()+"\n";    
}
System.out.println(s);
sc.close();
}

Upvotes: 0

Kevin Anderson
Kevin Anderson

Reputation: 4592

If you're looking to break your input file into pieces delimited by a blank line, something like this might work:

FileReader fr = new FileReader(//the txt file mentioned above); 
Scanner s = new Scanner(fr);
while (s.hasNext()){
    String paragraph = new String();
    while(s.hasNext()) {
        String line = s.next();
        if (line.length() == 0)
            break;
        if (paragraph.length() != 0)
            paragraph = paragraph + "\n";
        paragraph = paragraph + "\n" + line;
    }
    // Do something with paragraph here...           
}

Upvotes: 1

Related Questions