2016-08-11 18 views
-1

我想寫一個處理讀取文件的類。爲了逐字閱讀文件,我使用了我在互聯網上找到的以下代碼。 Netbeans似乎不同意,並表示它無法在while循環內找到symbole br。BufferReader裏面的try子句:找不到符號

public class Reader { 
    public String file2string() { 
    String line; 
    try (InputStream fis = new FileInputStream("smth")) { 
     InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); 
     BufferedReader br = new BufferedReader(isr); 
    } catch (IOException ex) { 
     Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    { 
     while ((line = br.readLine()) != null) { 
     String[] words = line.split(" "); 
     // Now you have a String array containing each word in the current line 
     } 
    } 
    return line; 
    } 
} 
+1

請縮進代碼,如果正常,你有求於人,試圖讀取它。 – khelwood

+1

你的'while循環'超出'try-catch',所以變量'br'超出了範圍 – SomeJavaGuy

回答

1

您的環路出於try,因此變量br在上下文中未知。把你的while-looptry結構裏面喜歡這裏:

public String file2string() { 
    String line = null; 
    try (InputStream fis = new FileInputStream("smth")) { 
     InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); 
     BufferedReader br = new BufferedReader(isr); 

     while ((line = br.readLine()) != null) { 
      String[] words = line.split(" "); 
      // Now you have a String array containing each word in the current line 
     } 
    } catch (IOException ex) { 
     Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    return line; 
} 
1

您在try語句

{ 
    InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); 
    BufferedReader br = new BufferedReader(isr); 
} 

然後,你還要另一個{}塊之後有{}塊。

{ 
    while ((line = br.readLine()) != null) { 
     String[] words = line.split(" "); 
     // Now you have a String array containing each word in the current line 
    } 
} 

在第一個塊中聲明的變量在第二個塊中不可見。

合併兩大塊:

public String file2string() { 
    String line; 
    try (InputStream fis = new FileInputStream("smth")) { 
     InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); 
     BufferedReader br = new BufferedReader(isr); 
     while ((line = br.readLine()) != null) { 
      String[] words = line.split(" ");   
     } 
     return line; 
    } catch (IOException ex) { 
     Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    // you need to decide what you want to return here if you got an exception. 
} 

你似乎分裂每一行,並忽略結果,然後返回文件的最後一行。我不知道你爲什麼這麼做,或者你實際上想做什麼;但是這是如何解決編譯錯誤。

+0

我該如何解決這個問題?我無法在輸入流讀取器之前聲明buffeedreader。 – Majd

+0

基本上,在'try'塊中放入使用'br' >>的代碼。 –

1

變量「br」在try {}塊中聲明,所以這是它的範圍。它在該塊之外將不可見。嘗試在try塊中放置while循環。