Sar*_*rah 0 java file method-call java-io
那么文件"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());}
}}
Run Code Online (Sandbox Code Playgroud)
exists()测试文件是否存在,因此在逻辑上是java.io.File类的一部分,而不是类String的一部分.所以代码应该是
File file = new File("MyStore.obj");
if (!file.exists()) {
throw new FileNotFoundException("file doesn't exist");
}
Run Code Online (Sandbox Code Playgroud)
在将FileInputStream打开到同一个文件之后执行此检查没有多大意义,因为如果文件不存在,FileInputStream已经抛出了FileNotFoundException,正如其javadoc所示.
| 归档时间: |
|
| 查看次数: |
2615 次 |
| 最近记录: |