簡體   English   中英

如何用Java讀取文件

[英]How to read files in Java

因此,我需要幫助修復此代碼,或者更多地了解其錯誤。 該代碼本身應該讀取文件並打印出出現的字符串字符串。 但是,即使.txt文件位於我的桌面上,它似乎始終會打印出“找不到文件”。

import java.util.*;
import java.io.*;

/**
 * Searcher
 */
public class Searcher extends File {

    Scanner scn;

    public Searcher(String filename) {
        super(filename);
    }

    public void search(String input) {

        try {
            scn = new Scanner(this);
            String data = "";

            while (scn.hasNext()) {
                data = scn.nextLine();
            }

            int count = 0, fromIndex = 0;
            while ((fromIndex = data.indexOf(input, fromIndex)) != -1) {
                count++;
                fromIndex++;
            }
            System.out.println("Total occurrences: " + count);

            scn.close();
        } catch (Exception e) {
            System.out.println("Cant find file ");
        }
    }

    public static void main(String[] args) {
        Searcher search = new Searcher("ihaveadream.txt");
        search.search("slavery");
    }
}

使用.txt文件的完整路徑,或將其移至項目其余部分所在的文件夾。 該程序不會檢查桌面(即使文件夾位於桌面中)。

您可以使用更優雅的方式通過Stream API讀取文件:

Files.lines(Paths.get(“ / home / userName / Desktop / text.txt”)).forEach(System.out :: println);

根據操作系統的不同,會有不同的路徑,但是文件必須有絕對路徑。

如果不想在OS桌面上創建文件,則可以在IDE上的當前類所在的程序包上創建文件,然后在main方法上指示文件目錄:在我的情況下: src/practice/ihaveadream.txt

public static void main(String[] args) {
        Searcher search = new Searcher("src/practice/ihaveadream.txt");
        search.search("slavery");
    }

我使用IntelliJ Idea Community ,因此您可以看到如何在Idea上創建文件: 在此處輸入圖片說明

use this code 

File file = new File("C:\\Users\\abc\\Desktop\\test.txt");// this is a path of your file

  BufferedReader br = new BufferedReader(new FileReader(file));

  String str;
  while ((str = br.readLine()) != null)
    System.out.println(str);

暫無
暫無

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

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