写一个java小程序使其能够从txt文件中一次读取一个字符的操作,怎么写?最好详细点

2024-12-21 15:57:30
推荐回答(3个)
回答1:

  try {
   InputStreamReader isr = new InputStreamReader(new FileInputStream(filename));
   int chr = -1;
   // isr.read()方法:返回读取的字符,如果已到达流的末尾,则返回 -1
   while ((chr = isr.read()) != -1) {
   // ...
   }
   } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   }


回答2:

FileInputStream

每次读多少,视乎逻辑需求的,read()就是读一个

回答3:

@Test
public void read() throws IOException{
String path = "your_file_path";
File file = new File(path);
if(!file.exists()){
throw new IllegalArgumentException("File path error!");
}
int i;
InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
while((i=reader.read())!=-1){
System.out.println((char)i);
}
}