0
import java.io.*;
import java.util.Scanner;
public class Test {
    /**
     * @param args
     */
    public static void main(String[] args) throws FileNotFoundException {
        File test = new File("test.txt");
        Scanner read = new Scanner (test);
        String input;
        input = read.next();
        System.out.println (input);
    }
}

When I run this code, I get this error

Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified)

at java.io.FileInputStream.open(Native Method)

at java.io.FileInputStream.<init>(Unknown Source)

at java.util.Scanner.<init>(Unknown Source)
    at Test.main(Test.java:9)

I have already created the text file and it is right in the project folder but it is not finding it.

EDIT

InputStream file = getClass().getResourceAsStream("highScore.txt");
BufferedReader br = new BufferedReader (new InputStreamReader(file,"UTF-8"));
String text;
text = br.readLine();
while (text!=null) {
    System.out.println (text);
}

I tried this but I got a NullPointerException error

This is for an applet.

Guo Toby
  • 1
  • 3

2 Answers2

0

You have to be in the same directory as test.txt when you start the program. For example:

cd dir/with/textfile
ls
  test.txt
java -cp my.jar com.toby.guo.Test

Alternatively, you could give the full path to the file:

File test = new File("/home/dir/with/textfile/test.txt");
Tim Pote
  • 27,191
  • 6
  • 63
  • 65
0

When you read a file using new File("test.txt"); the file should be directly inside the current-working-directory of your java program.

Or you can also put the file along with your Test.java and read it like:

Test.class.getResourceAsStream("test.txt");
Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94
  • Where is this directory? I've tried reading it that way and it works but I don't know how to change inputstream into string. – Guo Toby Jun 16 '12 at 05:27
  • And in this video :http://www.youtube.com/watch?v=x9c8PNLR8AU, the guy put the file in the project folder and it worked. – Guo Toby Jun 16 '12 at 05:33