繁体   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