Sebastian
Sebastian

Reputation: 15

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.

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");
    }
}

Upvotes: 0

Views: 4127

Answers (4)

Vishal Sharma
Vishal Sharma

Reputation: 1061

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);

Upvotes: 0

jundev
jundev

Reputation: 159

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

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: enter image description here

Upvotes: 0

Andrii Torzhkov
Andrii Torzhkov

Reputation: 301

You can use a more elegant way to read the file using the Stream API:

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.

Upvotes: 0

Cycl10ps
Cycl10ps

Reputation: 49

Use the full path for the .txt file or move it into the same folder as the rest of your project. The program won't check the desktop (even if the folder is in the desktop).

Upvotes: 1

Related Questions