• Post Reply Bookmark Topic Watch Topic
  • New Topic

URGENT .exists  RSS feed

 
Julie Maenhout
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

I'm trying to create a file before writing/reading to/from it. I always get an error that the package (although it is a file) doesn't exist. My code is as follows:

File myFile = new File(System.getProperty("user.dir") + File.separator
+ "\\output\\Daganalyse.pdf");
File parentDir = myFile.getParentFile();
if(parentDir.isDirectory())
{
parentDir.mkdirs();
}

It turns red at the 'if' and Netbeans gives following errors:
illegal start of type
package parentDir does not exist
<identifier> expected
';' expected


Please help me!
Thank you!
 
Julie Maenhout
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and of course, the correct code is: if (!parentDir.isDirectory()) (and I have the same problem with .exists), but it still turns red
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is that the entire code? If so, you're missing the class declaration (something like "public class FooBar {", and at least one import statement.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Julie. Welcome to the Ranch!

At a guess (without seeing the rest of the code), you've probably got that code directly in the class body. It needs to be inside a method.

In the class body the first two lines would be allowed, because they'd be interpreted as instance variable declarations. But you can't have other statements there, so the if statement would give that error - the compiler would be expecting the line to start with a type declaration.
 
Julie Maenhout
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're absolutely right! I figured it out by using different coding:

static String datum = "14-13-2012";
static String pathDir = "H:\\Weekanalyses";
//static String pathFile = "H:\\Weekanalyses\\newfile" + datum +".txt";
static int i =0;
static String pathFile = "H:\\ Leveranciers\\GoedkoopsteLeveranciers-" + i + ".txt";


public static void main(String[] args)
{File f = new File(pathDir);
try{
if(f.exists()==false){
f.mkdir();
System.out.println("Directory Created");
}
else{
System.out.println("Directory is not created");
}
}catch(Exception e){
e.printStackTrace();
}

try {

File file = new File(pathFile);

if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}

} catch (IOException e) {
e.printStackTrace();
}

Thank you for your help!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!