java - 如何覆盖 InputStream 方法 read() 以返回字符?

标签 java

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

问题是程序在中间崩溃并给出了未处理堆的错误,并且它没有在 out.txt

中打印最后一个词即 head

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

    }

}

最佳答案

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

System.out.print(a);

应该是

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

其次,流通过返回 -1 表示它已到达文件末尾。但是您总是将得到的内容转换为 char,而无需检查是否已达到结尾。所以读取方法应该是:

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
}

关于java - 如何覆盖 InputStream 方法 read() 以返回字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22129423/

相关文章:

java - jHipster:8080 和 9000 端口上的不同版本

java - HQL 从多对多映射中删除关联

java - 从 HttpServletRequest 获取目标 Controller

java - 如何设置单元格之间的空间以使单元格的内容不被删除

java - 计算最终长度

java - Zebra EM 220,使用 Android 打印 Code 128 条码

java - 寻找 Java 正则表达式以匹配给定范围内的最后 2 位数字

java - MQTT(Mosquitto)连接池?

JavaFX 按升序显示单词

Java方法参数给出编译错误 "Unexpected bound"