Simplest way to read a file using jcifs

倖福魔咒の 提交于 2019-12-10 11:13:50

问题


I am trying to read a file from a network share using the external jcifs library. Most sample codes I can find for reading files are quite complex, potentially unnecessarily so. I have found a simple way to write to a file as seen below. Is there a way to read a file using similar syntax?

SmbFile file= null;
try {
    String url = "smb://"+serverAddress+"/"+sharename+"/TEST.txt";
    NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, username, password);
    file = new SmbFile(url, auth);
    SmbFileOutputStream out= new SmbFileOutputStream(file);
    out.write("test string".getBytes());
    out.flush();
    out.close();
} catch(Exception e) {
    JOptionPane.showMessageDialog(null, "ERROR: "+e);
}

回答1:


SmbFile file = null;
byte[] buffer = new byte[1024];
try {
    String url = "smb://"+serverAddress+"/"+sharename+"/TEST.txt";
    NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, username, password);
    file = new SmbFile(url, auth);
    try (SmbFileInputStream in = new SmbFileInputStream(file)) {
        int bytesRead = 0;
        do {
            bytesRead = in.read(buffer)
            // here you have "bytesRead" in buffer array
        } 
        while (bytesRead > 0);
    }
} catch(Exception e) {
    JOptionPane.showMessageDialog(null, "ERROR: "+e);
}

or even better, assuming that you're working with text files - using BufferedReader from Java SDK:

try (BufferedReader reader = new BufferedReader(new InputStreamReader(new SmbFileInputStream(file)))) {
    String line = reader.readLine();
    while (line != null) {
        line = reader.readLine();
    }
}

And write with:

try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new SmbFileOutputStream(file)))) {
    String toWrite = "xxxxx";
    writer.write(toWrite, 0, toWrite.length());
}



回答2:


    try {
        String url = "smb://" + serverAddress + "/" + sharename + "/test.txt";
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(DOMAIN, USER_NAME, PASSWORD);
        String fileContent = IOUtils.toString(new SmbFileInputStream(new SmbFile(url, auth)), StandardCharsets.UTF_8.name());
        System.out.println(fileContent);
    } catch (Exception e) {
        System.err.println("ERROR: " + e.getMessage());
    }


来源:https://stackoverflow.com/questions/43487647/simplest-way-to-read-a-file-using-jcifs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!