【发布时间】:2017-02-23 09:28:37
【问题描述】:
我写了一段代码,如果是DataOutputStream。
但控制台没有显示我的预期。
控制台show No file given,我希望它在第二个try{} 中打印id 和name。
好像我被困在了 File 的输出流中。
请帮我找出问题所在...
import java.io.*;
public class DOutPut {
public static void main(String args[]) {
DataOutputStream dos;
FileOutputStream fos;
int id = 100;
String name = "Tanaka";
if (args.length <= 0) {
System.out.println("No file given");
System.exit(1);
}
try {
fos = new FileOutputStream(args[0]);
dos = new DataOutputStream(fos);
try {
dos.writeInt(id);
System.out.println("wrote a id: " + id);
dos.writeUTF(name);
System.out.println("wrote a name: " + name);
} catch (IOException e) {
// TODO: handle exception
System.err.println("IO error");
System.exit(1);
} finally {
fos.close();
dos.close();
}
} catch (IOException e) {
// TODO: handle exception
System.err.println("Opening/Closing error");
System.exit(1);
}
}
}
在这里我找到了解决方案。感谢所有回答我问题的人。
我应该使用参数运行它。因为代码fos = new FileOutputStream(args[0]) 需要一个参数。
我用 Eclipse 编写 Java 代码,我可以使用 Run - Run Configurations。
【问题讨论】:
-
那么控制台显示了什么,您期待什么?
-
你说控制台显示“没有给出文件”。你肯定知道这意味着什么,因为你是让程序打印出来的人!
-
@immibis 我还是没明白...我写了如果 args 的长度小于 0,则表示没有文件,所以打印
no file given。但我的期望是它显示wrote a id: 100, wrote a name: Tanaka... -
那么args的长度小于0。为什么args的长度小于0呢?您是否期望 args 的长度小于 0?
-
@immibis 谢谢。我刚开始学习java...我该如何纠正它?添加参数?我只想让它显示
wrote a id: 100, wrote a name: Tanaka
标签: java stream dataoutputstream