使用jcifs读取文件的最简单方法 [英] Simplest way to read a file using jcifs

查看:583
本文介绍了使用jcifs读取文件的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用外部 jcifs库从网络共享中读取文件。我可以找到的大多数用于读取文件的示例代码非常复杂,可能不必要。我找到了一种简单的方法来到文件,如下所示。有没有办法用类似的语法读取文件?

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


推荐答案

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

甚至更好,假设你正在处理文本文件 - 使用<来自Java SDK的code> BufferedReader :

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();
    }
}

并写道:

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

这篇关于使用jcifs读取文件的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆