0

好吧,文件“MyStore.obj”与我下载的表格一起附加。我应该阅读这个文件的内容,它是按照内容的顺序给出的。我怎样才能确定它是否存在?因为如您所见,我尝试使用该方法 exists() 但它不起作用

import java.io.*;

public class sheet{
public static void main(String[]args){
try{
FileInputStream fis=new FileInputStream("MyStore.obj");

if(("MyStore.obj").exists()==false) //what can i do to fix this?

throw new FileNotFoundException("file doesn't exist");

ObjectInputStream ois=new ObjectInputStream(fis);

int numOfStorageDevice=ois.readInt();
int numOfComputerGames=ois.readInt();

StorageDevice [] sd=new StorageDevice[numOfStorageDevice];

for(int n=0;n<numOfStorageDevice;n++)
 sd[n]=(StorageDevice)ois.readObject();

 ComputerGame []cg=new ComputerGame[numOfComputerGames];

 for(int m=0;m<numOfComputerGames;m++)

 cg[m]=(ComputerGame)ois.readObject();

   File file=new File("Result.txt");
    FileOutputStream fos=new FileOutputStream(file);
   PrintWriter pr=new PrintWriter(fos);

 for(int i=0;i<numOfStorageDevice;i++){

 String model= sd[i].getmodel(); 
  /*and in the methodcall sd[i].getmodel() it keeps telling that
    the symbol cannot be found but i'm sure that the method exists*/

 pr.println(model);}

for(int j=0;j<numOfComputerGames;j++){

pr.println(cg[j].getname());} 
 /*i keep getting the same problem with cg[j].getname() */
}
catch(FileNotFoundException e){System.out.print(e.getMessage());}
}}
4

2 回答 2

5

exists()测试文件是否存在,因此在逻辑上是java.io.File类的一部分,而不是 String 类的一部分。所以代码应该是

File file = new File("MyStore.obj");
if (!file.exists()) {
    throw new FileNotFoundException("file doesn't exist");
}

但是,在打开同一个文件的 FileInputStream 之后执行此检查并没有多大意义,因为如果文件不存在,FileInputStream 已经抛出了 FileNotFoundException,正如它的 javadoc所指示的那样。

于 2013-04-20T20:47:31.280 回答
1

尝试这个:

File data = new File("MyStore.obj");
if (!data.exists())
{
    System.out.println("File doesn't exist");
    System.exit(1);
}
FileInputStream fis = new FileInputStream(file); // and so on ...
于 2013-04-20T20:47:58.697 回答