2014-01-27 26 views
0

我已经学了Java大约一个月,目前正在学习Java的I/O,但是我遇到了一些问题。以下是使用Inputstream进行练习的简单玩具代码。意外的FileNotFoundException

import java.io.*; 

public class IOTest{ 
    public static void main(String[] args) throws IOException{ 
    InputStream in; 
    in = new FileInputStream(args[0]); 
    int total = 0; 
    while (in.read() != -1) 
    total++; 
    System.out.println(total + " bytes"); 
    } 
} 

上面的代码编译好了。这段代码的目的是简单地计算参数中有多少字节。然而,当我带参数运行编译后的代码,例如:

java IOTest firstTrial 

该系统提供了以下异常消息:

Exception in thread "main" java.io.FileNotFoundException: firstTrial <The system 
cannot find the file specified> 
     at java.io.FileInputStream.open(Native Method) 
     at java.io.FileInputStream.<init><Unknown Source> 
     at java.io.FileInputStream.<init><Unknown Source> 
     at IOTest.main<IOTest.java:8> 

请帮忙指出如何被抛出的异常?

另外一个问题是我使用Eclipse进行java编程。 Eclipse for Eclipse中的输入结束字符是什么?由于

+0

Ctrl + D用于EOF /输入结束 – Mike

+1

其中firstTrial文件存在? – Kick

+0

对不起,也许我没有让自己明白。我试图在运行代码期间读取参数并计算参数中的字节数。在上面的例子中,firtTrial是我在运行IOTest代码时输入的参数。 –

回答

0

你是不是读文件:

java.io.FileNotFoundException: firstTrial <The system 
cannot find the file specified> 

把一些完整文件路径作为参数,你的程序将续字节。

0

看来,如果你想读参数字符串本身作为InputStream,但方式FileInputStream作品就是String你通过它不是数据阅读,但文件的名打开并阅读。

但是,您可以将字符串本身作为数据读取。如果你想在Java中使用Reader API,或者你想将原始字节读为InputStream,那么你可以使用StringReader,来做到这一点。 (但你需要指定的字符编码。在这种情况下,我将其指定为“UTF-8”)。

import java.io.*; 

public class IOTest { 
    public static void main(String[] args) throws IOException { 
     byte[] bytes = args[0].getBytes("UTF-8"); 
     InputStream in = new ByteArrayInputStream(bytes); 
     int total = 0; 
     while (in.read() != -1) { 
      total++; 
     } 
     System.out.println(total + " bytes"); 
    } 
} 

请注意,我获得字符串中的字节,然后用ByteArrayInputStream代替一个FileInputStream来读取它们。我做了另外一个改变,这个改变是围绕着while循环体。我更喜欢在一条线上有环路,或者更好的是在身体周围放置支撑以使环路更加清晰(并且可能避免错误)。