2017-04-27 9 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

'String'連結を使用して、読み込んだ各行の後に改行(' \ 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(); 
} 
関連する問題