如何读取同一包内的文件

时间:2015-09-16 15:42:19

标签: java

我创建了一些代码,要求用户输入一个int值,然后将其传递给我的第一个名为parity()的方法。然后,Parity()将告诉用户它是奇数还是偶数。在该方法完成之后,我希望我的主程序打开与我的程序在同一个包中的文件,但是我的异常一直在用输出终止我的程序"文件未找到或无法打开&#34 ;我觉得这是一个简单的修复,但我正在尝试的很多东西并没有改变它。到目前为止,这是我的代码:

package davi0030;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Assignment01 {

        static void parity(int value){
            int finalValue = value % 2;
            if (finalValue == 0){
                System.out.println(value + " is an even int!");
                }
            else{
                System.out.println(value + " is an odd int!");
            }

        }

        static void findPair(int value2, Scanner inputStream){
            int total;
            int n1 = inputStream.nextInt();
            while (inputStream.hasNextLine()){
                total = 0;
                int n2 = inputStream.nextInt();
                total = n1 + n2;
                if (total == value2){
                    System.out.println("a pair is found: " +n1 + " and " +value2+ " add to " + total);
                    System.exit(0);
                }
                System.out.println("no pair in the file adds to" + total);

            }

        }

        public static void main(String[] args) {

            int value1;
            int value2;
            Scanner inputStream = null;
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Enter a positive integer, 0 to end:");
            value1 = keyboard.nextInt();
            while (value1 != 0){
                parity(value1);
                System.out.println("Enter a positive integer, 0 to end:");
                value1 = keyboard.nextInt();
            }
            if (value1 == 0){
                System.out.println("Congratulations, you passed the first test");
                try{
                    inputStream = new Scanner(new FileInputStream("numbers.txt"));
                }
                catch (FileNotFoundException e)
                {
                    System.out.println("File was not found or could not be opened");
                    System.exit(0);
                }
                System.out.println("file opened successfully");
                System.out.println("Enter a positive integer");
                value2 = keyboard.nextInt();
                findPair(value2, inputStream);
            }
            keyboard.close();
            System.exit(0);


        }
    }

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解了这个问题,但我可以告诉您,您可以阅读同一个包中的文件:

BufferedReader reader = new BufferedReader(new InputStreamReader(Assignment01.class.getResourceAsStream("numbers.txt"), "UTF-8"));