Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use a supplied username and password to read a file in Java

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

However, the folder that the files are in has limited permissions. I (i.e. my Windows username) have permissions to read them, but the user that Java runs as (this is part of a web application) does not. If I pass my own username and Windows network password into Java at runtime, is there a way I can read those files using my own permissions rather than the web user's?

(Note that this is NOT happening over the web; this is a one-time import script running in the context of a web application.)

like image 459
Jacob Mattison Avatar asked Oct 14 '22 13:10

Jacob Mattison


1 Answers

You could create a network share 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)
                {
                }
            }
        }
    }
}
like image 82
jt. Avatar answered Oct 18 '22 14:10

jt.