源文件如下package com.io;
import java.io.*;
public class CountBytes {
public static void main(String[] args) throws IOException{
InputStream in;
if(args.length==0)
in=System.in;
else
in=new FileInputStream(args[0]);
int total=0;
while(in.read()!=-1)
total++;
System.out.println(total+"bytes");
}
}
很简单的文件,但是就是没有输出结果,也没有任何的错误提示!初步怀疑是被阻塞了,但是不知道在哪里?
import java.io.*;
public class CountBytes {
public static void main(String[] args) throws IOException{
InputStream in;
if(args.length==0)
in=System.in;
else
in=new FileInputStream(args[0]);
int total=0;
while(in.read()!=-1)
total++;
System.out.println(total+"bytes");
}
}
很简单的文件,但是就是没有输出结果,也没有任何的错误提示!初步怀疑是被阻塞了,但是不知道在哪里?
你把main方法的throws IOException去掉
在程序里try,catch捕获,然后打印异常信息,看看是怎么回事
一定是出现异常了。
import java.io.*;public class CountBytes {
public static void main(String[] args) throws IOException {
System.out.println("Please input :");
InputStream in;
if (args.length == 0)
in = System.in;
else
in = new FileInputStream(args[0]);
int total = 0;
while (in.read() != -1){
System.out.println(total + "bytes");
total++;
} }
}
一楼的,main方法也可以加上throws语句,只是这里发生阻塞,就算是main方法的throws IOException去掉
在程序里try,catch捕获也是没有结果的!因为问题不在异常!2楼的:读到的完全有可能是-1,因为没有指定文件名的情况下,System.in文件的字节是318 bytes的啊!-1是到达流的末尾的返回值啊!
怎么回事啊?
如果是system.in的话,不知道你是想文件的内容呢,还是读你输入的内容呢,如果是计算输入内容的字节数就需要一个输入流用来读取输入内容!
结果只是输出
Please input :
还是没有下文……………………(你们分够高的,但是………………唉!)有点失望!!
从你的代码看,InputStream in = System.in;这个是从控制台读取输入用的,也就是键盘输入。
如2楼所说,没有得到-1的情况。所以一直处于堵塞状态。
在命令行输入文件路径时,因为运行的是 InputStream in = new FileInputStream(filename);
所以in.read()在文件最后会读到-1。