2014-03-02 31 views
2

問題是:開發一個ConvertToLowerCase派生自FileInputStream並重寫從FileInputStream派生的read()方法,使覆蓋read()方法返回一個小寫字符。使用此類將in.txt中的文件信息轉換爲小寫文本並將其寫入文件out.txt如何超過InputStream方法read()返回一個字符?

的問題是,該方案在中間崩潰,並給出未處理的堆錯誤,並且它不打印在out.txt

這裏的最後一個字,即頭部是在in.txt:

How High he holds His Haughty head 

這裏的out.txt:

how high he holds his haughty 

(注意這個詞頭缺失)

我找不出這個問題。任何幫助將不勝感激:)

//ConvertToLowerCase class 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
public class CovertToLowerCase extends FileInputStream { //inherits from FileInputStream 

public CovertToLowerCase(String name) throws FileNotFoundException { 
    super(name); 
    // TODO Auto-generated constructor stub 
} 


public int read() throws IOException { 
    char c=(char) super.read(); //calling the super method read 
    c=Character.toLowerCase(c); 
    return c; 
} 

} 

import java.io.FileOutputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 

public class HW4ex2 { 

public static void main(String[] args) throws FileNotFoundException { 
    CovertToLowerCase c1=null; 
    FileOutputStream output=null; 

    try { 


c1= new CovertToLowerCase("C:/Users/user/workspace/HW4ex2/in.txt"); 
    output= new FileOutputStream("C:/Users/user/workspace/HW4ex2/out.txt"); 
     int a; 
     while ((a=c1.read()) != -1) 
     { 
      System.out.print(a); 
      output.write(a); 

     } 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    } 

} 
+4

請解釋你的老師從InputStream繼承,用於讀取字節,而不是字符,是不正確的方法來解決這個問題。閱讀器用於閱讀字符。並且應該使用裝飾器模式。令人沮喪,真的要看老師給出這樣愚蠢的指示。 –

+0

我認爲可能會有某些EOF條件從某處讀取返回,並且不會轉換爲小寫字符。 – rethab

+0

我很抱歉,我剛剛編輯了代碼,它應該從FileInputStream繼承。 – user3367892

回答

1

好的。首先,你的主要方法打印整數,而不是字符。所以下面的一行

System.out.print(a); 

應該

System.out.print((char) a); 

其次,它已經通過返回-1到達文件的末尾流信號。但是你總是把你得到的東西轉換成字符,而不用檢查是否已經達到了。所以讀取方法應該是:

public int read() throws IOException { 
    int i = super.read(); //calling the super method read 
    if (i < 0) { // if EOF, signal it 
     return i; 
    } 
    return (Character.toLowerCase((char) i)); // otherwise, convert to char and return the lowercase 
} 
+0

非常感謝你。它現在有效! – user3367892

相關問題