6

I need to read CSV file header from FTP.

As these files can be very huge, I don't need to download them.

Is there a way to read first line of CSV file from FTP and abort connection?

Carl Manaster
  • 39,912
  • 17
  • 102
  • 155
Alexey
  • 517
  • 2
  • 10
  • 21

1 Answers1

15

Just read only the first line, ignore the remnant and close the stream. A smart FTP client won't buffer the entire stream in memory before providing anything for read.

Assuming you're using Apache Commons Net FTPClient:

BufferedReader reader = null;
String firstLine = null;

try {
    InputStream stream = ftpClient.retrieveFileStream(ftpFile.getName());
    reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
    firstLine = reader.readLine();
} finally {
    if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}

doYourThingWith(firstLine);
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555