1
我试图执行此代码,并且它主要工作。 但是,当我想要程序打印输入的数字(在finally部分中)时,程序不想要。 我做错了什么?我该如何修复它?无法从bin文件打印数据
public static void main(String[] args)
{
FileOutputStream outChannel = null;
DataOutputStream numberChannel = null;
Scanner kb = new Scanner(System.in);
int sum = 0;
int count = 0;
int highest = 0;
int number = 0;
String name = "";
try
{
System.out.println("Enter the name of the binary file: ");
name = kb.nextLine();
outChannel = new FileOutputStream(name);
numberChannel = new DataOutputStream(outChannel);
System.out.println("Enter negative value to stop.");
System.out.println("Enter scores: ");
while(true)
{
number = kb.nextInt();
if(number <0)
break;
numberChannel.writeInt(number);
sum+=number;
count++;
if(number>= highest)
highest = number;
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
catch(IOException e)
{
System.out.println("Cannot write file");
}
finally
{
Scanner fileReader = new Scanner(name);
while(fileReader.hasNextInt())
{
System.out.println(number);
}
fileReader.close();
System.out.println("Average: " + ((double)sum/(double)count));
System.out.println("Highest: " +highest);
try
{
if (numberChannel!= null)
numberChannel.close();
}
catch(IOException e)
{
}
}
}
所有帮助表示赞赏!
'FileOutputStream'用于写入原始字节流,如im年龄数据。为了编写字符流,请考虑使用FileWriter。请查看[oracle]的文档(https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html) –