检测文件是否存在

时间:2013-04-20 20:37:19

标签: java file java-io method-call

文件“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());}
}}

2 个答案:

答案 0 :(得分: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,如its javadoc所示。

答案 1 :(得分: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 ...