简体   繁体   中英

Reading an external txt file on main.class

I have a little question that, I have a blank main class, and the thing is that I want to know how can I read a external .txt file located on the package of main.java (tests package has main.java and LerDaqui.txt ) and I want to know how can I read and print the content from LerDaqui.txt to main.java .

Many thanks

BTW I did try to do this, but this is so simple that this is the only what to ask... Either way for some people to not call me lazy and that sort o stuff I got this code at least..

package testes;

import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {
        InputStream in  = Main.class.getClassLoader().getResourceAsStream("testes/LerDaqui.txt");
        String everything = "nao leu";
        BufferedReader br = new BufferedReader(new FileReader("testes/LerDaqui.txt"));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            everything = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            br.close();
        }
        System.out.println(everything);
    }
}

but this gives me FileNotFound Exception .....

The path you have mentioned in the FileReader is wrong... If file is in the same folder in which your java program is present then the path would be.

BufferedReader br = new BufferedReader(new FileReader("LerDaqui.txt"));

Input stream is not necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM