0
我想從文件讀取,但是我得到了一些奇怪的結果。以下是我的代碼。從文件讀取異常處理的怪異行爲
class A
{
try{
B writeToFile = new B();
B readFromFile = new B();
File file = new File("C:/Users/HB/workspace/A/src/xyz.txt");
boolean fileExists = file.isFile();
if (fileExists)
{
readFromFile.readFromFile();
}
if(...)
{
//my other code
}
else
throw new Exception (type_op);
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Incorrect number of arguments supplied to command.");
System.out.println("");
}
catch (Exception e)
{
System.out.printf("'%s' is not a valid command.%n",type_op);
System.out.println();
}
我在這裏做的是類A是我正在執行所有操作的主類。我正在執行某些操作,並且如果用戶輸入除上述以外的操作,則會拋出異常。在調試時,我看到找到了文件xyz.txt,編譯器進入readFromFile()。然而,在while循環,它會檢查文件中的數據,然後我拋出一個異常 -
'operation_inputted_on_console' is not a valid command.
我預計它從文件中讀取,並將其存儲在我的ArrayList。
class B
{
public void readFromFile() throws FileNotFoundException
{
Scanner inputStream = null;
inputStream = new Scanner(new FileInputStream("C:/Users/HB/workspace/A/src/xyz.txt"));
while(inputStream.hasNextLine())
{
attribute1=inputStream.next();
attribute2=inputStream.next();
attribute3=inputStream.next();
attribute4=inputStream.nextInt();
attribute5=inputStream.nextInt();
attribute6=inputStream.nextInt();
attribute7=inputStream.nextInt();
addPlayer(attribute1,attribute2,attribute3...);
}
inputStream.close();
}
public void writeToFile() throws FileNotFoundException
{
PrintWriter outputStreamName = new PrintWriter(new FileOutputStream("C:/Users/HB/workspace/A/src/xyz.txt",true));
int size = arrayList.size();
B obj;
//my code
for (int i=0;i<size;i++)
{
//my code
}
outputStreamName.close();
}
}
}
上面的代碼工作正常,如果我從我的類中刪除readFromFile()。 readFromFile在這裏引起這個問題的東西是錯誤的。
xyz.txt將該包含如下 -
a,a,a,2,0,2,0
b,b,b,2,2,0,0
c,c,c,2,1,1,0
a,a,a,1,0,1,0
b,b,b,1,1,0,0
//我的代碼?那裏有什麼? –
在您的'Exception'處理程序中,請打印您的堆棧跟蹤 - 例如'e.printStackTrace();' –
@Rod_Algonquin - 添加了代碼片段。 – MrCoder