0

我需要打印出用户使用 datainputstream
和 dataoutputstream 输入的数据,但这甚至没有正确输入。谁能告诉我
我的代码有什么问题?

import java.io.*;

class Employee
 {
int id;
String name;
double salary;
 }

public class Ch8Ex2 
 {
   public static void main (String[] args) 
   {
      Employee emp = new Employee();
      try
       {
         File f1 = new File("emp1.dat");
         f1.createNewFile();

         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         DataInputStream da = new DataInputStream(new FileInputStream(f1));
         DataOutputStream ad = new DataOutputStream(new FileOutputStream(f1));

         System.out.println("Enter your ID:");
         emp.id = br.read();
         System.out.println("Enter your name:");
         emp.name = br.readLine();
         System.out.println("Enter your salary:");
         String str = br.readLine();
         emp.salary = Double.parseDouble(str);

         ad.write(emp.id);
         ad.writeUTF(emp.name);
         ad.writeDouble(emp.salary);

         ad.flush();
         ad.close();

         System.out.println("ID:"+da.readInt());

         System.out.println("Name:"+da.readUTF());

         System.out.println("Salary:"+da.readDouble());

         da.close();
       }
        catch(IOException e)
        {

        }
        catch(NumberFormatException e)
        {

        }
     }
}
4

3 回答 3

2

假设这是唯一的事情

emp.id = br.read();

应该

emp.id = Integer.parseInt(br.readLine());

BufferedReader.read() 读取单个字符

除非当然id只是一个字符。

于 2013-01-01T12:26:36.270 回答
2

您需要使用ad.writeInt(emp.id),因为ad.write(int)只写入一个字节。

于 2013-01-01T12:35:02.167 回答
1

Employee必须是可序列化的

 class Employee implements Serializable
 {
   int id;
   String name;
   double salary;
 }

还在 catch 块中打印异常,然后你可以得到什么是错误的。

于 2013-01-01T12:11:57.667 回答