【发布时间】:2014-05-18 05:33:37
【问题描述】:
我正在尝试从文件中读取,但是我得到了一些奇怪的结果。下面是我的代码。
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 - 添加了代码 sn-p。
-
@ElliottFrisch - 为什么我需要使用 printStackTrace()?
标签: java file-io exception-handling