简体   繁体   English

如何用Java读取文件

[英]How to read files in Java

So I need help fixing this code, or more so understanding its faults. 因此,我需要帮助修复此代码,或者更多地了解其错误。 The code itself is supposed to read a file and print out the of occurrence of a string of words. 该代码本身应该读取文件并打印出出现的字符串字符串。 However, it seems that it always prints out "Can't find file" even when the .txt file is on my desktop. 但是,即使.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");
    }
}

Use the full path for the .txt file or move it into the same folder as the rest of your project. 使用.txt文件的完整路径,或将其移至项目其余部分所在的文件夹。 The program won't check the desktop (even if the folder is in the desktop). 该程序不会检查桌面(即使文件夹位于桌面中)。

You can use a more elegant way to read the file using the Stream API: 您可以使用更优雅的方式通过Stream API读取文件:

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

Depending on the operating system, there will be different paths, but there must be an absolute path to the file. 根据操作系统的不同,会有不同的路径,但是文件必须有绝对路径。

If you do not want to create a file on your OS desktop, you can just create a file on IDE on a package in which the current class is, then indicate the file directory on main method: in my case : src/practice/ihaveadream.txt 如果不想在OS桌面上创建文件,则可以在IDE上的当前类所在的程序包上创建文件,然后在main方法上指示文件目录:在我的情况下: src/practice/ihaveadream.txt

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

I use IntelliJ Idea Community , so you can see how to create a file on Idea: 我使用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