gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:21:41 25 4
gpt4 key购买 nike

问题是:开发一个派生自 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com