如何过度使用InputStream方法read()来返回一个字符?

时间:2014-03-02 15:20:42

标签: java

问题是:开发一个源自ConvertToLowerCase的类FileInputStream并覆盖从read()派生的FileInputStream方法,以便覆盖read()方法返回小写字符。使用此类将in.txt中的文件信息转换为小写文本,并将其写入文件out.txt

问题是程序在中间崩溃并且给出了未处理堆的错误,并且它不打印最后一个单词,即out.txt

中的头部

这是in.txt:

How High he holds His Haughty head

这是out.txt:

how high he holds his haughty 

(注意单词head缺失)

我无法弄清楚问题。任何帮助将不胜感激:)

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

    }

}

1 个答案:

答案 0 :(得分:1)

行。首先,您的main方法打印整数,而不是字符。所以以下一行

System.out.print(a);

应该是

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

其次,流通过返回-1表示它已到达文件末尾。但是你总是把你得到的东西转换成char,而不用检查是否已达到目的。所以read方法应该是:

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
}