0

Hello everyone,

I'm working on an assignment that requires the use of the Scanner class to read the source code of the .java file and output all lines when executed. I have created a file that works without issues on my machine, but I was wondering if there was a more robust way to reference the file location. Currently, the code has a static file location that is only true for my system, and I would like it to function regardless of the drive or directory. Any references or ideas are appreciated.

//************************************************************************************************************************************************************************
//Assignment for Module 3: Assignment3.java
//Dan 
//U#
//September 16th, 2012
//Quine -Java program designed to utilize Scanner class to read source code and then display code to user at execution; no input is required of user.
//************************************************************************************************************************************************************************

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

public class Assignment3 {


    public static void main(String[] args) throws FileNotFoundException {
        Scanner inFile = new Scanner(new FileReader("C:/Users/Danimal/Documents/Fall 2012/EEL4854 IT Data Structures/src/Assignment3.java"));

            while (inFile.hasNextLine())  
                System.out.println(inFile.nextLine());  


    }

}
3
Contributors
3
Replies
5
Views
4 Years
Discussion Span
Last Post by dnanassy
0

yes there is, place that file with the jar, or in a folder with the jar.
Like FILES in folder. then reference throught
FILES//file-name
Thats how you can make it dynamic, it will work on all platform.

0
  1. Use a file open dialog and let the user chose the file. (Easy, but requires user involvement)
  2. Use System.getProperty("user.home") to get the user's home directory and place the file there (or in a specified sub-directory). There's always a user home dir, even though it may be in completely different places in different operating systems. (Easy, safe, recommended.)
  3. Get the directory where the .class file is running from, and place the file there (but the code to get it is a bit tricky).
  4. Just use the file name and put the file in the current working directory (but it's one of the great mysteries in Java to know where that dir will be!)
  5. Give the file a unique name then do a recursive traversal of all the attached file systems to find that file (the code for that is fun, but could be slow)

Edited by JamesCherrill

0

Thank you for the input. It was very helpful. I'm still working on modifying the code, will update when complete.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.