日期:2014-05-20  浏览次数:20841 次

求救输入输出的程序无法运行
下面是我的一本书里的程序,功能是把键盘输入的字符串首先保存到文件中,然后在将文件中的内容读取出来。我已经按照程序的要求在编译好的当前类的目录下新建了一个叫myData的目录,并且还在目录里新建了叫text.dat的文件,可是我运行的时候达不到预期的目的,看了好长时间都看不出出什么问题了,请各位高手不吝赐教

mport java.io.*;

public class FileInOutput
{
  public static void main(String[] args)
  {
  byte[] inCh = new byte[100];
  byte[] outCh = new byte[100];
  int bytes = 0;
  System.out.println("请输入一些字符串:");
  try
  {
  bytes = System.in.read(inCh, 0, 100);
  }
  catch (IOException e)
  {
  System.out.println(e.toString());
  }
  File myFile1 = new File("myData", "test.dat");
  if (myFile1.exists())
  {
  try
  {
  System.out.println("将开始输入的字符写入到文件中。");
  FileOutputStream fout = new FileOutputStream(myFile1);
  fout.write(outCh);
  fout.close();
  System.out.println("已结束将字符输入写入到文件中.");
  System.out.println("开始从文件中读出已写入的内容。");
  FileInputStream fin = new FileInputStream(myFile1);
  bytes = fin.read(inCh, 0, 100);
  fin.close();
  String inStr = new String(inCh);
  System.out.println("从文件中读出的字符串内容是:" + inStr);
  }
  catch (IOException e)
  {
  System.out.println(e.toString());
  }
  }
  System.out.println("按任意键继续…");
  try
  {
  bytes = System.in.read();
  }
  catch (IOException e) {}
  }
}

------解决方案--------------------
修改下代码就可以了,主要错误原因:1,FILE的构造函数,你用的的是File(String parent, String child)那应该先指定父路径;2,是fout.write(outch) 应该改成inch

public class FileInOutput 

public static void main(String[] args) 

byte[] inCh = new byte[100]; 
byte[] outCh = new byte[100]; 
int bytes = 0; 
System.out.println("请输入一些字符串:"); 
try 

bytes = System.in.read(inCh, 0, 100); 

catch (IOException e) 

System.out.println(e.toString()); 

File myFile1 = new File("D:/myData/test.dat"); 
if (myFile1.exists()) 

try 

System.out.println("将开始输入的字符写入到文件中。"); 
FileOutputStream fout = new FileOutputStream(myFile1); 
fout.write(inCh); 
fout.close(); 
System.out.println("已结束将字符输入写入到文件中."); 
System.out.println("开始从文件中读出已写入的内容。"); 
FileInputStream fin = new FileInputStream(myFile1); 
bytes = fin.read(inCh, 0, 100); 
fin.close(); 
String inStr = new String(inCh); 
System.out.println("从文件中读出的字符串内容是:" + inStr); 

catch (IOException e) 

System.out.println(e.toString()); 


System.out.println("按任意键继续…"); 
try 

bytes = System.in.read(); 

catch (IOException e) {} 

}