473,657 Members | 2,627 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

checking to see if a directory exists

112 New Member
Hi.
I am writing a java program in which I want to ftp a file to another unix box.
First I have to check if the directory exists in which I am ftping into and if it does not exist, I have to create it:

this is the code that I am using that is not working properly:

Expand|Select|Wrap|Line Numbers
  1.            System.out.println("YOU ARE IN UPLOAD");
  2.            System.out.println("THIS IS THE HOST: " + host);
  3.            SshClient ssh = new SshClient();
  4.            ssh.connect(host, 22);
  5.          //Authenticate
  6.            PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();
  7.            passwordAuthenticationClient.setUsername(user);
  8.            passwordAuthenticationClient.setPassword(password);
  9.            System.out.println("upload user and password: " + user + password);
  10.            int result = ssh.authenticate(passwordAuthenticationClient);
  11.            if(result != AuthenticationProtocolState.COMPLETE){
  12.                System.out.println("Login to " + host + ":" + " " + user + "/" + password + " failed");
  13.        }
  14.          //Open the SFTP channel
  15.            SftpClient client = ssh.openSftpClient();
  16.          //Send the file
  17. //Debugging Print Statements
  18.            System.out.println("UPLOAD LOCALEFILE IS: " + localeFile);
  19.            remoteDirFile = "/sbt/prod/infra/run_dir/tmp/nancy";
  20.            System.out.println("UPLOAD REMOTEDIRFILE IS: " + remoteDirFile);
  21.  
  22.            File devstorDir=new File(remoteDirFile);
  23.            boolean exists = devstorDir.exists();
  24.            if (!exists) {
  25.                   // It returns false if File or directory does not exist
  26.                   System.out.println("the file or directory you are searching does not exist : " + exists);
  27.                   System.out.println("DEVSTORDIR is: " + devstorDir);
  28.                   boolean successCreatingDir = devstorDir.mkdir(); 
  29.                   if (!successCreatingDir) { 
  30.                       // Directory creation failed 
  31.                       System.out.println("DIRECTORY: " + remoteDirFile + " WAS NOT CREATED: " + successCreatingDir);
  32.                       }
  33.                   else{
  34.                       System.out.println("GREAT SUCCESS IN CREATING A DIRECTORY: " + successCreatingDir);
  35.                                   System.out.println("YOU ARE AT THE PUT NOW");        
  36.            client.put(localeFile, remoteDirFile);
  37.                   }  
  38.  
  39.            }else{
  40.                   // It returns true if File or directory exists
  41.                   System.out.println("the file or directory you are searching does exist : " + exists);
  42.                   System.out.println("DEVSTORDIR is: " + devstorDir);
  43.                                 System.out.println("YOU ARE AT THE PUT NOW");        
  44.            client.put(localeFile, remoteDirFile);
  45.            }
  46.  
  47.  
  48.            //disconnect
  49.            client.quit();
  50.            ssh.disconnect();
  51.  
I test the code by creating and deleting the directory on my test machine and then running the program and on each occasion, if the directory does or does not exist, I still get a false, saying that directory does not exist and it does not create a new directory.
Since i am doing this inside of an FTP, does the mkdir() and the exists() methods not work or something?

Thanks for the help!!!
Jan 13 '10 #1
4 14928
pbrockway2
151 Recognized Expert New Member
Have you checked the documentation for the SftpClient class? I would have guessed that the client instance is what lets you check for the existence of directories, create them and copy files etc. And not the Java File methods which are for naming files that are already part of your computer's file system.
Jan 13 '10 #2
pbrockway2
151 Recognized Expert New Member
Just a guess but are we talking about com.sshtools.j2 ssh?

If so, instead of "if(exists) {" you would say

Expand|Select|Wrap|Line Numbers
  1. client.stat(remoteDirFile);
  2.  
(I'm not sure if this is null if the directory doesn't exist, or whether it throws an IOException).

There is also

Expand|Select|Wrap|Line Numbers
  1. client.mkdirs(remoteDirFile);
  2.  
which like it's Java counterpart does not fail if the directory already exists.
Jan 13 '10 #3
ndedhia1
112 New Member
Hey pbrockway2,
thanks a lot for your help!!
I am working with com.sshtools.j2 ssh
I got the mkdirs to work which makes the directory for me if it does not exist and if it does exist, it does nothing, which is what it is supposed to.
I wasnt able to get the client.stat(rem oteDirFile) to work yet where i can check if a directory exists already, but I got most of what i needed to work!!
I am still pretty new to java so i am trying to figure out how to create my own exception and what to do when an exception is throw. I catch it but I want to create the dir and then go back to where i need to be in the code. Still trying to figure that out.

thanks again for the help!!!
Jan 14 '10 #4
pbrockway2
151 Recognized Expert New Member
I've never used com.sshtools.j2 ssh (I just thew the class names at Google and had a look at what came back). The documentation says to use stat() before mkDirs() - I'm guessing but the reason might be so that you don't clobber a file with the same name as a directory on your new path. However they don't say how...

Exceptions are well dealt with in Sun's Tutorial. Well worth knowing about, but my suggestion that stat() would throw an exception was just thinking aloud. Thinking about it today it seems to me a little counterintuitiv e for it to throw an exception: after all you are checking for the existence of a file and nonexistence is hardly exceptional. You're best bet would be to find some usage instructions for the package from whereever you downloaded it. Or get creative with Google.

Anyway I'm glad you've got mkdirs() working as you want.
Jan 14 '10 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

3
2864
by: Rob Meade | last post by:
Hi all, I am allowing a user to create a directory within my application. I have them entering the name for the directory in a form. When the form is processed I initially check for any special characters that are not allowed (Windows based server incidently), from here I then need to check to see whether the folder name has already been used (either by a previous entry using the application etc, or reserved names as such ie, /images...
15
114201
by: Geiregat Jonas | last post by:
is using if(open("file",O_EXCL) != -1){ printf("File does exists")}else{printf("file does not exists"); } a good way of checking if a file exists or not, if not how should I do it ?
1
3999
by: Kerem Gümrükcü | last post by:
Hi, how can i find out, whether a given string specifies a Path or a file... System.IO.File.Exist(UnknownString) does not work for my application. i exactly need to know if the strng is a path or a file... But how the h*** can i find it out....
9
1653
by: Sheldon Cohen | last post by:
Hello, I am using c# and running a site that is on a shared host. The code in question is supposed to create a new directory that is coming out of a text box. It works fine on my computer, but I get the following stack trace: System.IO.DirectoryNotFoundException: Could not find a part of the path "D:\". at System.IO.__Error.WinIOError
1
1966
by: ledder77 | last post by:
Hi, I need to find a way to check if a relative url exists on the server. I cannot use WebRequest.Create method because it needs a complete URI. Any suggestion? Thanks in advance Francesco
2
4937
by: John Smith | last post by:
1. Which is the best way to check the existence of a given directory using vb.net? .Net 1.1. 2. Which is the best way to check the existence of a given file using vb.net? .Net 1.1. Drive includes mapped network drive also. Thank you,
11
16836
by: Daz | last post by:
Would anyone know of a way to check whether or not a particular path is a directory? If I have to go down the route of using _findfirst and _findnext (windows specific), then so be it. However, I don't think it should be that difficult to check. My original idea was to check to see if the path can be opened with fstream, but this can give false results if the path is a filename, and the file cannot be opened. I am using boost, and can't...
7
19079
by: sprash | last post by:
Newbie question: I'm trying to determine if a file physically exists regardless of the permissions on it Using File.Exists() returns false if it physically exists but the process does not have the necessary permissions. One hack could be to check for length and that would throw a FileNotFoundException ...but there is got to be a better way!
0
1232
by: emp | last post by:
I am writing a logging function. Hourly a log entry is made into a directory for the current date. Each day a new current date directory is made. How can I check to see if a directory exists? Is there some way better than systeming off a mkdir? I am using g++ in a unix box so the windows CreateDirectory is not an option. I had hoped that I could just create a string that contained the complete path including the log file name, open it...
0
8392
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7324
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6163
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4302
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1953
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1611
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.