2017-01-16 17 views
0

ユーザーのために単純なテキストファイルを読み込んで表示していると思います。何か助けていただきありがとうございます。Javaでtxtファイルを読み込もうとしています

import java.io.*; 
import static java.lang.System.in; 
import java.util.Scanner; 

public class PersonReader 
{ 
    public static void main(String[] args) throws FileNotFoundException, IOException 
    { 
     Scanner reader = new Scanner(System.in); 
     String textFile = SafeInput.getString(reader, "What file would you like to read?: "); 
     try(BufferedReader br = new BufferedReader(new FileReader(textFile + ".txt"))) 
     { 
      StringBuilder sb = new StringBuilder(); 
      String line = br.readLine(); 
      while (line != null) 
      { 
       sb.append(line); 
       sb.append(System.lineSeparator()); 
       line = br.readLine(); 
      } 
      String everything = sb.toString(); 
     } 
    } 
} 
+0

あなたのコードにはどのような問題がありますか?バグ?コンパイルしませんか? – jackarms

+4

画面に何も印刷しません。私はあなたがそれをする方法を知っていると思います。 –

+2

@NirajPatelこれは完璧です。 Java 7以降に存在するtry-with-resourcesステートメントについて読んでください(これはずっと前です)。 –

答えて

0

最終的なstringbuilder文字列は印刷されませんでした。

import java.io.*; 
import java.util.Scanner; 

public class PersonReader { 
    public static void main(String[] args) throws FileNotFoundException { 
     Scanner reader = new Scanner(System.in); 
     System.out.println("What file would you like to read?: "); 
     String textFile = reader.nextLine(); 

     File f = new File(textFile + ".txt"); 
     if (f.isFile()) { 
      Scanner sc = new Scanner(f); 
      StringBuilder sb = new StringBuilder(); 
      while (sc.hasNextLine()) { 
       sb.append(sc.nextLine() + System.lineSeparator()); 
      } 
      System.out.println(sb); 
      sc.close(); 
     } 
     else { 
      System.out.println("could not find file: " + textFile + ".txt"); 
     } 
     reader.close(); 
    } 
} 
+0

ありがとうございました! – user7427726

関連する問題