Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中正确测试instanceof_Java_Ioexception_Instanceof_Eofexception - Fatal编程技术网

如何在java中正确测试instanceof

如何在java中正确测试instanceof,java,ioexception,instanceof,eofexception,Java,Ioexception,Instanceof,Eofexception,我正在用Java测试一个ObjectInputStream。当我包含if语句时,我得到一个EOF错误。如何正确测试进入流的对象?输入流对象的类型为字节[]数组 if (ObjectInputStream.readObject() instanceof byte[]) { // what to get the new file System.out.println("Getting File"); fileFromServer = new File("/Users/josh

我正在用Java测试一个
ObjectInputStream
。当我包含if语句时,我得到一个EOF错误。如何正确测试进入流的对象?输入流对象的类型为
字节[]数组

if (ObjectInputStream.readObject() instanceof byte[]) {
    // what to get the new file
    System.out.println("Getting File");
    fileFromServer = new File("/Users/joshuataylor/git/swd_jtylor/oral_exam2/27-13_FileRetrieve_Easy/src/output.txt");
    byte[] fileContent = (byte[]) ObjectInputStream.readObject();
    System.out.println(fileContent.length);
    Files.write(fileFromServer.toPath(), fileContent);
    ObjectOutputStream.flush();

    message = "End Connection";
    System.out.println("eof");
}

当前,您正在通过
ObjectInputStream.readObject()
读取两个对象-一个在条件中,另一个在if块中

您应该只调用一次
ObjectInputStream.readObject()
,并将其存储在变量中:

Object obj = ObjectInputStream.readObject();
if (obj instanceof byte[]) {
    // what to get the new file
    System.out.println("Getting File");
    fileFromServer = new File("/Users/joshuataylor/git/swd_jtylor/oral_exam2/27-13_FileRetrieve_Easy/src/output.txt");
    byte[] fileContent = (byte[]) obj;
    System.out.println(fileContent.length);
    Files.write(fileFromServer.toPath(), fileContent);
    ObjectOutputStream.flush();

    message = "End Connection";
    System.out.println("eof");
}
进入“if”条件的readObject()读取该对象,因此进入“if”主体的下一个readObject()会发现该对象为空

即使它有一些缺点,您也应该将其包装在try中,捕获EOFEException并删除“if”。 请注意,在许多情况下都可能引发该异常,例如被截断的文件

try {
  ...
  byte[] fileContent = (byte[]) ObjectInputStream.readObject();
  ...
  }
}
catch (EOFException e){
... // exit the reading loop
}

您的实例变量不能一次以大写字母开头;而且肯定不会与现有类同名。另外,您是否意识到您从输入流中读取了两次?