V
V
Vitaly Voskobovich2015-04-25 09:26:45
Java
Vitaly Voskobovich, 2015-04-25 09:26:45

How to implement reading a file via FTP from the desired location in Java?

The second day I'm looking for a solution.
Now there is a connection to the server, reading from the GZ stream and counting the bytes received last time. Downloaded files will have a weight of under 2 Gb.
Here is my code:

InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
StringBuilder stringBuilder = new StringBuilder();
String line;

try {
    URI uri = new URI("ftp", "user:pass", "localhost", 21, "/file.gz", null, null);
    URL url = uri.toURL();
    FtpURLConnection connection = (FtpURLConnection) url.openConnection();

    int countBytes = 0;

    inputStream = connection.getInputStream();
    inputStream = new GZIPInputStream(inputStream);
    inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);

    int bytes;
    char ch;
    while ((bytes = inputStreamReader.read()) != -1) {
        ch = (char) bytes;
        countBytes += 1;

        if (ch != '\n') {
            stringBuilder.append(ch);
        } else {
            line = stringBuilder.toString();
            System.out.println(line);

            stringBuilder = new StringBuilder();
        }
    }

} catch (IOException | URISyntaxException e) {
    e.printStackTrace();
} finally {
    try {
        assert inputStream != null;
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        assert inputStreamReader != null;
        inputStreamReader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    stringBuilder = null;
    line = null;
}

How to pass offset when reading from a file via FTP?
The Range header only works for the HTTP protocol.
I'm at a dead end(
PS: Comments on the code and its optimization are welcome.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
relgames, 2015-05-20
@relgames

lmgtfy.com/?q=java+ftp+resume+download

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question