简体   繁体   中英

Cannot find file on netbeans

I'm trying to access a data file to get questions and answers for my "Quiz" application. If I access the file from the one on my desktop, it works fine. If I drag and drop the file into my netbeans, I cannot seem to access it. The file is in the package "quiz" along with my other classes. Here's the code that works but I want to use the netbeans file.

String fileName = "C:/Users/Michael/Desktop/QUIZ.DAT";
 try {
        //Make fileReader object to read the file
        FileReader file = new FileReader(new File(fileName));
        BufferedReader fileStream = new BufferedReader(file);
    } catch (Exception e) {
        System.out.println("File not found");
    }

To try and access the file on netbeans I use this but it cannot find it.

String fileName = "quiz/Quiz.DAT";

Try this, where MyClass is the class name. I have assumed the quiz.dat file is in the same package of the class.

InputStream f = MyClass.class.getResourceAsStream("QUIZ.DAT");
BufferedReader bReader = new BufferedReader(new InputStreamReader(f));
StringBuffer sbfFileContents = new StringBuffer();
String line = null;
while ((line = bReader.readLine()) != null) {
    sbfFileContents.append(line);
}
System.out.println(sbfFileContents.toString());

JJPA provided proper code. But let me enhance it better.

Project
   com.io
      test.txt
   com.root
      AccessFile.java

This is my program structure. I want to access file from package io So here is the code.

package com.root;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class AccessFile {
    public static void main(String args[]){
        try{
            InputStream f = AccessFile.class.getResourceAsStream("../io/test.txt");
            BufferedReader bReader = new BufferedReader(new InputStreamReader(f));
            StringBuffer sbfFileContents = new StringBuffer();
            String line = null;
            while ((line = bReader.readLine()) != null) {
                sbfFileContents.append(line);
            }
            bReader.close();
            f.close();
            System.out.println(sbfFileContents.toString());
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

如果您试图在JAVA项目中读取文件,而netbeans找不到该文件,则将该文件放在项目的根目录中,它应该可以找到它。

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