Dan Tepper
Dan Tepper

Reputation: 23

Taking input and using it to find and read files

I've created a method which reads a file which is in the same folder as the class. I then return the text inside the file and run other methods with it.

I now need to adapt it so that the user can input a file name to be read however I am unsure on how to edit my existing code to do that. Here's what I have now.

public static String fileReader()
{
    String str2 = "";
            try {
                Scanner sc =
                new Scanner(new FileInputStream(
                        "C:\\Users\\AaranHowell\\eclipse-workspace\\UniWork\\UniWork\\src\\Assignment\\Untitled 2"
                        ));
                while (sc.hasNext()) {
                  str2 = sc.nextLine();
                }
                sc.close();
              } catch (IOException e) {
                System.out.println("No file can be found!");
              }
            return str2;

Any help is much appreciated!

Thanks,

Aaran

Upvotes: 1

Views: 32

Answers (2)

Quazan
Quazan

Reputation: 79

If you want to get user input use:

Scanner scanner = new Scanner(System.in);
String fileName = scanner.nextLine();

You can just pass fileName argument to fileReader() function and append it at the end of filepath.

String filePath = "C:\\Users\\AaranHowell\\eclipse-workspace\\UniWork\\UniWork\\src\\Assignment\\" + fileName;

Remember to specify extension to the file you want to open.

Scanner sc = new Scanner(new FileInputStream(filePath));

Upvotes: 1

Sudhir Ojha
Sudhir Ojha

Reputation: 3305

You can use Scanner class to take input from user and you can change your fileReader() to accept file name as input fileReader(String fileName).

public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter file name:");
        System.out.println(fileReader(sc.next()));
        sc.close();

    }

    public static String fileReader(String fileName) {
        String str2 = "";
        String directory = "C:\\Users\\AaranHowell\\eclipse-workspace\\UniWork\\UniWork\\src\\Assignment\\";
        try {
            Scanner sc = new Scanner(new FileInputStream(directory + fileName));
            while (sc.hasNext()) {
                str2 += sc.nextLine();
            }
            sc.close();
        } catch (IOException e) {
            System.out.println("No file can be found!");
        }
        return str2;
    }

Upvotes: 1

Related Questions