【问题标题】:Detect if the file exists检测文件是否存在
【发布时间】:2013-04-20 20:37:18
【问题描述】:

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

【问题讨论】:

  • 我已经从你的代码墙上删除了空行,但我强烈建议编辑它并添加适当的缩进(也考虑删除不相关的代码,如 println)。
  • @AlexeiLevenkov 好的,谢谢我刚刚做了

标签: java file java-io method-call


【解决方案1】:

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 所指出的那样。

【讨论】:

  • 但是我们不是在创建一个同名的新文件吗?因为对象文件“MyStore.obj”已经存在
  • File 表示文件系统上的路径(存在与否)。创建多个实例不会导致任何问题。并且创建 File 实例不会在磁盘上创建任何物理文件。而且您的代码无论如何都不会创建任何 File 实例。
【解决方案2】:

试试这个:

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 ...

【讨论】:

  • 为什么? FileInputStream 无论如何都会抛出 FileNotFoundException 。这是多余的。
  • @EJP 这是多余的。此外,还提供了一个竞态条件。但这就是问题所在。
  • 有时问题的答案是“你不想那样做”。而不是提供原始钝刀的锋利版本。
猜你喜欢
  • 2013-04-12
  • 2012-10-25
  • 2016-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
相关资源
最近更新 更多