简体   繁体   English

Java-从头开始从流中读取文件

[英]Java - read file from stream from the end

i wonder if there is a way to read text file line by line from the end from FTP server. 我想知道是否有一种方法可以从FTP服务器的末尾逐行读取文本文件。 I need to read large file, and I'm interested only in the last few lines. 我需要读取大文件,并且仅对最后几行感兴趣。

I am able to read last line from file on my HD with code from this question: Quickly read the last line of a text file? 我可以使用以下问题的代码从硬盘上的文件中读取最后一行: 快速读取文本文件的最后一行? , and I am able too to read file on FTP server line by line with code from there: Java. ,而且我也可以通过那里的代码逐行读取FTP服务器上的文件: Java。 Read file from FTP but DON'T download it whole . 从FTP读取文件,但是不要全部下载

But in first case function tail uses variable type File, while second code uses variable type InputStream. 但是在第一种情况下,函数tail使用变量类型File,而第二种代码使用变量类型InputStream。

When I was looking for way of conversion stream to file, I found that only real way is download content to tmp file ( How to convert InputStream to virtual File ). 当我寻找将流转换为文件的方法时,我发现只有真正的方法是将内容下载到tmp文件( 如何将InputStream转换为虚拟File )。 But I don't want to download this file, because it may be be very large, as I wrote. 但我不想下载此文件,因为它可能非常大,如我所写。

Does anybody know another way to do this? 有人知道另一种方法吗?

It's not possible. 这是不可能的。 But you can read the input stream line by line and remember the only few last lines. 但是您可以逐行阅读输入流,并记住最后几行。 If the next line comes, just forget the first read line. 如果下一行到来,只需忘记第一读行即可。

It is not possible using the FTP protocol. 无法使用FTP协议。 The protocol only supports fetching the file starting at the beginning. 该协议仅支持从头开始获取文件。 (There is an optional feature that allows an interrupted transfer to be restarted half way through, but it depends on the server sending opaque "markers" that represent possible resumption points. I cannot see how you could use this to skip to the end of an arbitrary file.) (有一项可选功能,允许中断的传输在中途重新启动,但这取决于服务器发送的不透明“标记”代表可能的恢复点。我看不到如何使用它来跳到结尾任意文件。)

If you are looking at alternatives, consider using HTTP with a combination of HEAD requests, and GET requests with Range headers. 如果您正在寻找替代方案,请考虑将HTTP与HEAD请求和带有Range标头的GET请求结合使用。 (This depends on the server recognizing those requests ...) (这取决于服务器识别这些请求...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM