Question

Well the file "MyStore.obj" was attached along with the sheet I downloaded. And i'm supposed to read this file's content which is given with order of the contents.how can i make sure if it exists or not? because as you can see i tried using the method exists() but it didn't work

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());}
}}
Was it helpful?

Solution

exists() tests if a file exists, and is thus, logically, part of the class java.io.File, and not of the class String. So the code should be

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

Doing this check after opening a FileInputStream to the same file doesn't make much sense though, since the FileInputStream would already have thrown a FileNotFoundException if the file doesn't exist, as its javadoc indicates.

OTHER TIPS

Try this:

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 ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top