开发者

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 c开发者_运维百科ontext of a web application.)


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)
                {
                }
            }
        }
    }
}


If the files are on a network-share you could use the net tool. With

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

to open and close the share. I guess that should work

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜