0

Sorry but I am quite new to Java. I wanna write java code to read a text file which is in the same folder of the Java file. Can you guys give me some example codes? Many Thanks!

  • 1
    As a rule, you shouldn't have the file you are reading in the same folder as your Java file. Java files should be structured in packages. See the link above for details on how to get the actual path of the running .jar file – Scherling Feb 20 '14 at 08:44
  • Please clarify. Is the file in the same source package as the `.java` file? Or is it located in the bin directory with the `.jar` file? – Matt Clark Feb 20 '14 at 10:16

1 Answers1

1

If java class file and text file is in same directory. See How to get the path of a running JAR file? as Christopher suggested above.

You can Read a file like below in Java :

package com.Test.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {

public static void main(String[] args) {

    BufferedReader br = null;

    try {

        String sCurrentLine;

        br = new BufferedReader(new FileReader("D:\\XYZ.txt"));

        while ((sCurrentLine = br.readLine()) != null) {
            System.out.println(sCurrentLine);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}
}

See also : best-way-to-read-a-text-file

Community
  • 1
  • 1
Hars
  • 169
  • 2
  • 12