Reading the first bytes of a file

I need a very simple function that allows me to read the first 1 bytes of a file via FTP. I want to use it in MATLAB to read the first lines and, in some ways, to load only the files that I really need in the end. I found some examples online that, unfortunately, do not work. Here I offer a sample code where I try to upload a single file (I use Apache libraries).

FTPClient client = new FTPClient(); FileOutputStream fos = null; try { client.connect("data.site.org"); // filename to be downloaded. String filename = "filename.Z"; fos = new FileOutputStream(filename); // Download file from FTP server InputStream stream = client.retrieveFileStream("/pub/obs/2008/021/ab120210.08d.Z"); byte[] b = new byte[1024]; stream.read(b); fos.write(b); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } 

The error is in a stream that returns empty. I know that I am passing the folder name incorrectly, but I don’t understand how to do it. I tried a lot.

I also tried with Java Java classes like:

  URL url; url = new URL("ftp://data.site.org/pub/obs/2008/021/ab120210.08d.Z"); URLConnection con = url.openConnection(); BufferedInputStream in = new BufferedInputStream(con.getInputStream()); FileOutputStream out = new FileOutputStream("C:\\filename.Z"); int i; byte[] bytesIn = new byte[1024]; if ((i = in.read(bytesIn)) >= 0) { out.write(bytesIn); } out.close(); in.close(); 

but it gives an error when I close the InputStream!

I am definitely stuck. Some comments would be very helpful!

+6
source share
3 answers

Try this test

  InputStream is = new URL("ftp://test: test@ftp.secureftp-test.com /bookstore.xml").openStream(); byte[] a = new byte[1000]; int n = is.read(a); is.close(); System.out.println(new String(a, 0, n)); 

it definitely works

+1
source

From my experience, when you read bytes from a stream received from ftpClient.retrieveFileStream for the first run, it is not guaranteed that you are filling your byte buffer. However, either you must read the return value stream.read(b); surrounded by a loop based on it, or use the extended library to fill in 1024 bytes of length []:

 InputStream stream = null; try { // Download file from FTP server stream = client.retrieveFileStream("/pub/obs/2008/021/ab120210.08d.Z"); byte[] b = new byte[1024]; IOUtils.read(stream, b); // will call periodically stream.read() until it fills up your buffer or reaches end-of-file fos.write(b); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); } 
0
source

I do not understand why this does not work. I found this link where they used the Apache library to read 4096 bytes each time. I read the first 1024 bytes, and this works in the end, the only thing is that if fullPendingCommand () is used, the program is held forever. So I deleted it and everything works fine.

-1
source

All Articles