Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何超越InputStream方法read()返回字符?_Java - Fatal编程技术网

Java 如何超越InputStream方法read()返回字符?

Java 如何超越InputStream方法read()返回字符?,java,Java,问题是:开发一个从FileInputStream派生的类ConvertToLowerCase,并重写从FileInputStream派生的read()方法,以便重写read()方法返回小写字符。使用此类将in.txt中的文件信息转换为小写文本,并将其写入文件out.txt 问题是程序在中间崩溃,并给出未处理堆的错误,它不打印最后一个字,即在 Out.TXT 中的头。 以下是in.txt文件: How High he holds His Haughty head 下面是out.txt文件: h

问题是:开发一个从
FileInputStream
派生的类
ConvertToLowerCase
,并重写从
FileInputStream
派生的
read()
方法,以便重写
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一词已丢失)

我想不出这个问题。任何帮助都将不胜感激:)


嗯。首先,主方法打印整数,而不是字符。那么下面的一行呢

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
}
public int read()引发IOException{
int i=super.read();//调用super方法read
如果(i<0){//如果EOF,则发出信号
返回i;
}
return(Character.toLowerCase((char)i));//否则,转换为char并返回小写
}

请向您的老师解释,从用于读取字节而非字符的InputStream继承不是解决此问题的正确方法。读取器用于读取字符。应该使用装饰图案。令人沮丧的是,真的看到老师给出如此愚蠢的指示。我想在某个时候可能会从read返回一些EOF条件,并且这些条件不能转换为小写字符。对不起,我刚刚编辑了代码,它应该从FileInputStream继承。那个注释对我没有帮助。我不是自愿这么做的,这是别人要求我做的。谢谢你,谢谢:)
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
}