Acces to protected network files in java

Hi, I need to access files on a network (private LAN) via a java program.
I need to provide a username and a password in order to access these files, becouse they are not accessible by guests (Microsoft Windows 2000 network).
I saw Authenticator class and setDefault() method to provide username and password via getPasswordAuthentication() to an httpURLConnection: IT WORKS FINE, but unfortunately this is not an httpURLConnection...
So, I have to open a networked file, lets say :
java.io.File sourceFile = new File("\\\\MYSERVER\\MYSHARE\\HELLO.TXT");
and then read it, lets say :
java.io.FileInputStream in = new FileInputStream(sourceFile);
byte[] buffer = new byte[16384];
int len;
while ((len = in.read(buffer)) != -1) {
// do something
} // end of while
in.close();
I get a :
java.io.FileNotFoundException: \\MYSERVER\MYSHARE\HELLO.TXT (Access is denied)
How can I introduce a username and password in this context ?
thanks in advance,
Andrea

Windows file sharing networking is via SMB, which Java doesn't support. So, either make a native call (use JNI + C++) or implement SMB on TCP/IP in Java (not trivial - see Samba for details).

Similar Messages

  • What path to use to access network files from Java app running on Mac

    I have a Java app running on a Mac with OS X that I'm using to check for files that exists on Windows servers within our network.
    Using a path like /Volumes/<Share>/ works because I've already connected to the drive using Finder. If I try to use a fully qualify the path with "smb://<Server>/<Share>" then my app doesn't see anything. Is there any way that I can get Java to connect to a directory without first having mapped or made the connection via some external tool like Finder?
    Here's the code I'm testing with:
    package FileImports;
    import java.io.File;
    import java.util.Arrays;
    public class Dir {
    static int indentLevel = -1;
    static void listPath(File path) {
    File files[];
    indentLevel++;
    files = path.listFiles();
    if (!(files == null)){
    Arrays.sort(files);
    for (int i = 0, n = files.length; i < n; i++) {
    for (int indent = 0; indent < indentLevel; indent++) {
    System.out.print(" ");
    System.out.println(files.toString());
    if (files[i].isDirectory()) {
    listPath(files[i]);
    indentLevel--;
    } else System.out.println("Directory not accessible!");
    public static void main(String args[]) {
    // this path works where <share> = the directory where my files exist.
    listPath(new File("/Volumes/<share>"));
    // this path returns a null result in files
    // listPath(new File("smb://<Server>/<Share>/"));
    Thanks,
    Alex
    Edited by: agates on Sep 25, 2008 11:14 AM

    agates wrote:
    Thanks for the response. I'll have to dig a little deeper into JCIFS. It looks like it would work great windows to windows. I haven't been able to find in the documentation where it would work on OS X without having to mount the targeted file system first. Has anyone had success creating a connection to a windows file system from OS X with JCIFS?Since jCIFS is written in pure Java and implements the entire SMB/CIFS protocoll on it's own it doesn't require any support from the OS (apart from a normal JVM runnig). Thus it should work exactly the same in OS X and Windows (and Linux and Solaris and ...).

  • How to open a network file in java ?

    File c = new File("directory");
    like this ?
    but how to define the directory ?

    If the file is on a shared drive "mounted" as some local drive letter, you can use that drive letter, or you can use the UNC notation in Java as in any other program.
    for Microsoft Windows platforms, the prefix of a pathname that contains a drive specifier consists of the drive letter followed by ":" and possibly followed by "\" if the pathname is absolute. The prefix of a UNC pathname is "\\"; the hostname and the share name are the first two names in the name sequence. A relative pathname that does not specify a drive has no prefix.

  • Password protected Excel file generation using Java

    Hi,
    I want to create password protected excel file using Java. So when you manually open this file it should prompt for password.
    There are APIs but they are licensed and are for trial period. I want solution which is free.
    I need this solution urgently..
    :-)

    Swati.S wrote:
    Hi Administrator,
    Moderator. Administrators post with the Sun logo.
    I'm sorry I wasnt aware that we cannot have off forum communication. Can you please communicate how I can spread this message taht solution for this is available.If you like, you can post the code here or on [SDN Share|http://sdnshare.sun.com/]. Apart from that, there's no shortage of blog sites.

  • Command for Unzipping a password protected zip file in Solaris

    Hi,
    I got a requirement where I need unzip a password protected zip file using java in Solaris.I tried with
    unzip -P but it is not working in India and Australia (may be I need to download some patch). Can any one help me to find out the solution.
    Thanks
    Naresh

    Hi peterchun,
    Thanks for your reply.
    I was trying with correct password only but my Solaris is not able to recognize unzip -P command. Can you please let me know whether I need to install any patch on Solaris (my Solaris version is 9) for this command.
    Basic requirement: password protected zip files comes to our application and those need to be unzipped to one particular location. As we are using JAVA/J2EE in our application, Can you please suggest any UNIX command (with example) for this requirement will be great.
    Thanks,
    Naresh

  • Unzip a password protected file in java where the passwd is known

    How do i unzip unzip a password protected file in java n the password is known.
    Unzipping a simple zip file in java can be done thru Zip package but it provides no option for password protected files.
    If anybody knows plse help me out.

    You can't with Java standard classes.

  • How to read some records from a text file into java(not all records)

    hello,
    how to read text files into java. i need only few records from the text file not all records at a time.
    If any one knows plz reply me
    my id is [email protected]

    this snipet reads a text file line by line from line 1 to 3
    try {
                  FileReader fr = new FileReader(directory);
                  BufferedReader br = new BufferedReader(fr);
                  int counter = 0;
                  while ((dbconn = br.readLine()) != null) {
                      switch(counter){
                          case 0:
                            status = dbconn;
                          break;
                          case 1:
                            userName = dbconn;
                          break;
                          case 2:
                            apword = dbconn;
                          break;
                      counter++;
                  br.close();
        }catch(IOException e){
        }

  • Class file to java file conversion

    is it possible to convert .class file into .java file & if yes
    then how to convert .class file into .java file.
    plz. mail me ans. on [email protected] | [email protected]

    Yes there are many Java Decompilers which converts the Java bytecode class files to Source files, You may find the follwing URLs helpful:
    http://www.brouhaha.com/~eric/computers/mocha.html
    http://members.fortunecity.com/neshkov/dj.html

  • How to read the data from Excel file and Store in XML file using java

    Hi All,
    I got a problem with Excel file.
    My problem is how to read the data from Excel file and Store in XML file using java excel api.
    For getting the data from Excel file what are all the steps i need to follow to get the correct result.
    Any body can send me the code (with java code ,Excel sheet) to this mail id : [email protected]
    Thanks & Regards,
    Sreenu,
    [email protected],
    india,

    If you want someone to do your work, please have the courtesy to provide payment.
    http://www.rentacoder.com

  • Monitoring of a file in java

    Hi All,
    Can anyone tell me that can we monitor a file in java which is available in a Shared Location in my system.
    I just want to log the user information,time of access of the file.
    Can anyone help me in this situation?
    Thanks in advance
    Senthil Kumar.S

    If you are on Windows there is an API ReadDirectoryChangesW that you can call using JNI. This call is supposed to block until the file is changed. At that point your code can check to see what happened.
    I tried using it a while back but found it to be problematic. It could just be that it was my first attempt at JNI and I was doing something wrong, but I eventuallu gave up and created a thread that simply polled the file every 2 seconds. In my case the file was on a local driver so there really wasn't much overhead. You may want to think twice about doing this over the network, however.
    If you want to try to use the JNI call I found most of my information here
    HTH

  • I can't open or save file with Java Web Start

    Hi,
    i can't open or save file with Java Web Start:
    import java.io.*;
    import java.util.*;
    public class MetaDataFileCreator {
    public String fileNameSpace = null;
    public String fileName = null;
    protected Properties file = null;
    public MetaDataFileCreator(String fileNameSpace, String fileName) {
    this.fileNameSpace = fileNameSpace;
    this.fileName = fileName;
    public void createMetaDataFile() {
    try {
    System.out.println("file METADATA");
    ClassLoader cl = this.getClass().getClassLoader();
    String nameFileMetaData = fileNameSpace + fileName + ".txt";
    FileOutputStream fileOS = new FileOutputStream(cl.getResource(nameFileMetaData).getFile());
    file = new Properties();
    file.setProperty("aaaaa", "aaaa");
    file.store(fileOS, "");
    fileOS.close();
    } catch (Exception e) {
    System.out.println("Error writing metadata-file: " + e);
    System.exit(1);
    e.printStackTrace();
    I have try also to open a file like this:
    ClassLoader cl = this.getClass().getClassLoader();
    file.load(cl.getResourceAsStream(nameFile));
    also like this:
    try {
    fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
    fss = (FileSaveService)ServiceManager.lookup("javax.jnlp.FileSaveService");
    } catch (UnavailableServiceException e) {
    fss = null;
    fos = null;
    System.out.println("Error with JNLP");
    System.exit(1);
    if (fss != null && fos != null) {
    try {
    // get a FileContents object to work with from the
    // FileOpenService
    FileContents fc = fos.openFileDialog(null, null);
    //FileContents newfc2 = fss.saveAsFileDialog(null, null, fc);
    // get the OutputStream and write the file back out
    if (fc.canWrite()) {
    // don't append
    os = fc.getOutputStream(false);
    } catch (Exception e) {
    e.printStackTrace();
    also like this:
    File f = new File((System.getProperty("user.home")+"x.txt").toString());
    FileOutputStream fileX = new FileOutputStream(f);
    OutputX = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fileX, "UTF8")));
    OutputX.println(....
    but it doesn't work with Java Web Start.
    Can someone help me?
    How can I open or save file?
    thank you.
    Sebastiano

    Did you specify <all-permissions/> in your JNLP file? Did you sign your code? What error are you getting?

  • Running a batch file in Java. Urgent!!

    I want to run a batch file present at a particular location in Java.Although I am running two codes suggested by many people, i am still not able to run the batch file. My codes run as below :-
    CODE 1
    Process P;
    Runtime rt = Runtime.getRuntime();
    P = rt.exec("C:\\test.bat");
    CODE 2
    Process P;
    Runtime rt = Runtime.getRuntime();
    P = rt.exec("C:\\WINNT\\System32\\cmd.exe C:\\test.bat");
    I have tried both these codes but without success. But I have observed that in the Task Manager, whenever i run the above codes in a servlet, a "CMD.EXE" is being created in the "Processes" Bar each time but the batch file neither opens up nor it runs.
    Please suggest me some method to run this batch file in Java.
    Or if u can suggest the reason behind the above observation and any corrections i can make to run the batch file. Thanks in advance.
    Ankit

    i want to get more than one command prompt while running the program
    am giving the problem
    import java.io.*;
    class CmdDemo
         CmdDemo(String ls) {
              try
              Process p;
              Runtime rt=Runtime.getRuntime();
              p=rt.exec(ls);
              catch(IOException ioe)
                   System.out.println(ioe);
         void showcmd(){
    new CmdDemo("cmd");
         public static void main(String args[])
              new CmdDemo("cmd");
              new CmdDemo("C:/WINDOWS/System32/cmd.exe");
              new CmdDemo("cmd");
              new CmdDemo("regedit");
              new CmdDemo("regedit");
              new CmdDemo("notepad");
              new CmdDemo("notepad");
              //CmdDemo cd=new CmdDemo("cmd");
              //cd.showcmd();
    here am getting two notepads ,two registry editors
    but only one command window
    i would be very greateful if u could help me
    plz reply to my id [email protected] too

  • Progmatically save to password protected network folder

    I am looking to save a file to a password protected network folder.  I tried using the standard Write Text.vi to see if a dialog would pop up, but it did not.  There is not an ftp server running on the networked computer, so I dont think that will work.
    The IT department directions to the folder say:  Go to Start> Run and enter url \\computername\folder\subfolder\...  and a dialog will appear to enter username and password.
    Any ideas??
    Thanks
    Kenny

    muks wrote:
    Well this is what we do. Run--->(doubleslash(\\) computername slash(/) d$)
    Eg: \\pc48\d$ .When you get a popup(U should) type the username and password of the that computer having admin rights.
    That simply reiterates what the IT department originally told the poster to do, except that you're using the administrative share. 
    Kenny K wrote:
    I should have noted that there
    should be no user interaction, ie they should not be entering the
    username and password, the program should login and save the file
    automatically.  sorry.
    To do this you will need to delve into the Windows API. You can also use .NET to perform impersonation. Most of the examples that are on the internet are based on .NET 1.1 and it's probably easier to simply create yourself a custom class that you can call using a single method rather than trying to put all the .NET code into LabVIEW. An example of using impersonation (though there are lots of them) can be found here. 

  • Deleting default trace file in java

    Hello all,
    Whats the best way to automatically delete default trace file in java instance? I want to delete these files lets say every week or 2 wkkds,Is there any type of configuration that can be done through NWA or OS...? or do i have to write some scripts? Please advice.

    Perfect.
      When set to 10, 0 -->9 are cyclic files. Regarding archiving, yes this is possible. Apart from defaulttrace files you can also archive other java log files (system, network,security etc). The configuration procedure is explained :-
    http://help.sap.com/saphelp_nw04/helpdata/en/48/2edfd5bd3e0d4a81b90325fe195a70/frameset.htm
    Once the 10th trace file(i.e.defaultrace9) is full, all the trace files (from defaulttrace0-defaultrace9) are zipped to a single file. The file compression ratio is extremely good.
    Unfortunately there is no automated mechanism to clear off the archived files. This needs manual intervention(regular cleanup, script etc).
    The archived log files may also be viewed for analysis from NWA.
    While estimating the size for each defaulttrace consider  three factors  i) System load ii) Number of defaulttrace files.
    iii) Retention days(without archiving)
    Ex: System load as observed :
    Say the trace file size is 10MB and 6 trace files get written in 4 hours of peak time and 1 trace files is written for 4 hours during non-peak time .Assuming 8 hours of peak business hours and rest all non-working hours.
    No of files generated is 62 + 14 = 16 files of 10 MB each are generated per week day
    If the defaulttrace file  count is set to 16, you can retain one days' logs . Say you wish to retain the same with less number of files (i.e. 8) you would have to increase the file size to 20 MB. Also will have to look at file system space availability.
                   CAUTION: For a file system occupancy estimate, you will have to also consider as to how many Server nodes are 
                                    configured as each node has its own log area !
    For this you need to observe the pattern as to how many files are being written then estimate the size and count
    cheers !
    PRADi

  • How Do I create set up file of java

    Hello,
    I'm new to java up to I created litile small swing application.
    As per the instructon on java turorial I created jar file and it run
    properly.Now I want to create asetup file so that When I bring
    my file to another machine that dont hava jre installed it first
    install jre on that machine and allow me to run my programme.
    Hope U understand!
    Please send me reply on my yahoo id [email protected]
    thanks,

    I think Java web start comes with jre itself.
    It auto install java web start in to ur system when
    you install jre.That is correct.

Maybe you are looking for

  • Open down payment request

    Hi Could you please let me know the table where I can check all open down payment request with indicator F? Thanks Sweta

  • How many photos are too many photos for iPhoto? When do I need to upgrade to Aperture?

    How many photos are too many photos for iPhoto? When do I need to updgrade to Aperture?

  • Using non-XML content in a report key

    I have the desire within a proxy service to log a particular key/value pair in a report log where the key value is not within any XML document I have. Basically, during the logic within the proxy service, the service has come up with a specific resul

  • App-V 4.6 applications on Windows 8

    Hello, Has anyone met a problem where after installing App-v 4.6 created package on Windows 8 which contains several shortcuts one of shortcuts is not appearing in start menu but if open all shortcut location it is there. Also when removing one of th

  • Bug in Bw statistics

    Hi gurus, I have a strange problem in BW Statistics. As you know the key of RSDDSTAT table is STATUID, and for each navigation should be one entry in this table. The problem is that in BW Statistics query I got the number of navigations, for one STAT