2017-04-27 52 views
0

例如停止,給定一個txt文件:的Java:閱讀文件,並在新行上下文

words 
123 
words:123 
words:324 

words 
123 
words:123 
words:324 

是否有可能做到這一點?

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; 
    } 

是否有可能只讀到空行?因此款將等於:

words 
123 
words:123 
words:324 
+0

只要使用串連接,並在讀取的每行之後加上一個換行符('\ n')。 – Logan

回答

1

如果你正在尋找打破你的輸入文件到一個空行分隔件,這樣的事情可能工作:

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...   
} 
+0

這是關鍵:'if(line.length()== 0)break;' – Barett

0

看看這有助於

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(); 
}