无法获取文件类找到已经存在的文件

时间:2018-11-19 01:27:03

标签: java file io

我正在尝试制作一个程序,提示用户输入,然后从输入中创建文件对象,并通过重新提示用户来处理文件是否不存在。香港专业教育学院尝试了绝对路径和相对路径,但它总是评估为false。任何帮助表示赞赏

package Module6B;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;


public class Module6 {
    public static void main(String[] args) throws FileNotFoundException {


        Scanner scan = new Scanner(System.in);
        Boolean exceptionThrown = false;
        String origin = "default";
        String destination = "destination";
        String contents = "";

        do {
                exceptionThrown = false;
            try{

                    System.out.println("enter the name of the existing file you want to copy");
                    origin = scan.next();
                java.io.File original = new java.io.File("C:\\Users\\Samme\\git\\1322-LAB\\src\\Module6B\\"+origin + ".txt");

                    if(original.exists()) {
                        contents = readFile(origin);
                    }else {
                    throw new FileNotFoundException();
                    }


            }catch(FileNotFoundException e) {
                    System.out.println("the file with the name you entered was not found enter a "
                            + "1 if you would like to try again and enter a valid file name or a 0 if you "
                            + "would like to exit the program");
                    int response = scan.nextInt();
                    if(response == 1) {
                    exceptionThrown = true;
                    }else {
                        System.out.println("Thank you for your time");
                        System.exit(1);
                    }
            }

1 个答案:

答案 0 :(得分:0)

package com.badri.test;

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

public class Test {
    public static void read(String fileName) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
        bufferedReader.close();
    }

    public static void main(String args[]) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter file name");
        String fileName = scanner.next();
        String filePath = "D://" + fileName + ".txt";
        if (null != filePath) {
            Test.read(filePath);
        }
    }

}