How to use the provided username and password to read a file in Java

I need to read a bunch of binaries from a Java script running on Windows.

However, the folder in which the files are located has limited permissions. I (for example, my Windows username) have permissions to read them, but the user who runs Java (this is part of the web application) does not support. If I pass in my own Windows network username and password to Java at runtime, is there a way so that I can read these files using my own permissions and not the web user?

(Note that this does NOT happen over the Internet, this is a one-time import script that runs in the context of a web application.)

+5
source share
2 answers

You can create a network resource and then connect via jCIFS

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.UnknownHostException;

import jcifs.smb.SmbException;
import jcifs.smb.SmbFileInputStream;

public class Example
{
    public static void main(String[] args)
    {
        SmbFileInputStream fis = null;
        try
        {
            fis = new SmbFileInputStream("smb://DOMAIN;USERNAME:PASSWORD@SERVER/SHARE/filename.txt");
            // handle as you would a normal input stream... this example prints the contents of the file
            int length;
            byte[] buffer = new byte[1024];
            while ((length = fis.read(buffer)) != -1)
            {
                for (int x = 0; x < length; x++)
                {
                    System.out.print((char) buffer[x]);
                }
            }
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
        catch (SmbException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (fis != null)
            {
                try
                {
                    fis.close();
                }
                catch (Exception ignore)
                {
                }
            }
        }
    }
}
+4
source

If the files are on a network share, you can use the net tool . FROM

runtime.exec("net use ...")

to open and close the resource. I think this should work

0
source

All Articles