javajcifs

Simplest way to read a file using 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);
}

Solution

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