java - 如何正确测试java中的instanceof

标签 java ioexception instanceof eofexception

我正在 Java 中测试 ObjectInputStream。当我包含 if 语句时,出现 EOF 错误。如何正确测试进入流的对象?输入流对象的类型为byte[]数组

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 block 内。

您应该只调用一次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");
}

关于java - 如何正确测试java中的instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33798257/

相关文章:

java - 在 Jaspersoft 中处理复杂类型(列表和对象)的正确方法是什么?

java - 如何将圆圈移动到 "WEST"边框布局框?

java - 无法运行 COMPS 应用程序。 ClassNotFoundException异常

android - 从 android 中的 HttpURLConnection 获取响应代码

javascript - Object.create 和原型(prototype)链的 Instanceof 等效项

java - Maven 3 不从本地存储库更新快照依赖项

java - Solr 错误 #500 IOE

java - 对象通用父类(super class) java instanceof

javascript - instanceof 在 javascript 中的奇怪输出

java - 以编程方式从远程 Maven 存储库下载工件