嗨我的Java程序應該讀入並顯示一個.txt文件,用戶在出現提示時輸入,將文件中的整數轉換爲輸出.dat文件,然後讀入該.dat文件並再次顯示數字。當我運行我的程序時,它會顯示文件的內容,並創建.dat文件,但不會再讀入它。我的代碼如下。我需要做什麼?爲什麼我的程序不能打開我的.dat文件?
public class InputFile
{
public static void main(String [] args)
{
BufferedReader inputStream = null;
System.out.print("Enter file name (with .txt extension): ");
Scanner keys = new Scanner(System.in);
String inFileName = keys.next();
try
{
inputStream = new BufferedReader (new FileReader(inFileName));
System.out.println("The file " + inFileName + " contains the following lines:");
String inFileString = inputStream.readLine();
while(inFileString != null)
{
System.out.println(inFileString);
inFileString = inputStream.readLine();
}
inputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println(inFileName + " not found! Try Again.");
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
String fileName = "numbers.dat";
try
{
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
int anInt = 0;
while(anInt >=0);
{
anInt = Integer.parseInt(inputStream.readLine());
outputStream.writeInt(anInt);
}
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("Problem opening file.");
}
catch(IOException e)
{
System.out.println("Problem with output to the file.");
}
try
{
ObjectInputStream inputStream2 = new ObjectInputStream(new FileInputStream(fileName));
System.out.println("The file being read yields:");
int anInteger = inputStream2.readInt();
while(anInteger >= 0)
{
System.out.println(anInteger);
anInteger = inputStream2.readInt();
}
inputStream2.close();
}
catch(FileNotFoundException e)
{
System.out.println("Problem with opening the file.");
}
catch(EOFException e)
{
System.out.println("Problem reading the file.");
}
catch(IOException e)
{
System.out.println("There was a problem reading the file.");
}
}
}
你可能應該結合前兩個'while'循環。 – irrelephant
對不起,我更新Java。它編譯並運行時沒有任何錯誤消息。和@irrelephant,你會如何建議我這樣做? – Derek