簡體   English   中英

如何用Java讀取一個巨大的HTML文件?

[英]How to read a huge HTML file in Java?

我有一個要求,必須在我的應用程序的前端讀取和顯示一個巨大的HTML文件。 HTML文件大小約為25MB。 試過幾個選項,如:

Option 1:
    try (Scanner scnr = new Scanner(file);) {
                while (scnr.hasNextLine()) {
                    String line= scnr.nextLine();
                }
    } 
Option 2:
    FileUtils.readFileToString(file, "UTF-8");
Option 3:
    IOUtils.toString(new FileInputStream(new File(file)), "UTF-8")

以上3個選項都無法讀取文件。 我沒有看到錯誤。 處理剛剛停止,網頁會彈出一個沒有信息的“錯誤”彈出窗口。

問題似乎是整個HTML文件內容被讀取為單行字符串。

有沒有辦法可以讀取這個文件?

我在這里經歷了其他幾個問題,看看是否有可能的解決方案,但似乎沒有任何問題適用於這種情況。

@ user811433,我做了一些測試,使用Apache Commons IO讀取大小約為800MB的日志文件,並且執行時沒有發生錯誤。

此方法為文件打開InputStream。 完成迭代器后,應關閉流以釋放內部資源。 這可以通過調用LineIterator.close()或LineIterator.closeQuietly(LineIterator)方法來完成。

如果你像Stream一樣逐行處理,推薦的使用模式是這樣的:

File file = new File("C:\\Users\\lucas\\Desktop\\file-with-800MB.log");

    LineIterator it = FileUtils.lineIterator(file, "UTF-8");
    try {           
        while (it.hasNext()) {
            String line = it.nextLine();
            // do something with line, here just sysout...
            System.out.println( line );
        }
    } finally {
        LineIterator.closeQuietly(it);
    }

一些額外的參考, 這里這里

try {
            File f=new File("test.html");
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
            String content=null;

            while((content=reader.readLine())!=null)
            {
                  System.out.println(content);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM