exclu
exclu

Reputation: 49

How to read from a file that has no extension in Java?

So basically say i have a file that is simply called settings, however it has no extension, but contains the data of a text file renamed. How can i load this into the file() method in java? simply using the directory and file seems to make java think its just a directory and not a file.

Thanks

Upvotes: 3

Views: 6822

Answers (4)

Daniel
Daniel

Reputation: 28084

In Java, and on unix, and even on the filesystem level on windows, there is no difference in if a file has an extension or not.

Just the Windows Explorer, and maybe its pendants on Linux, use the extension to show an appropriate icon for the file, and to choose the application to start the file with, if it is selected with a double click or in similar ways.

In the filesystem there are only typed nodes, and there can be file nodes like "peter" and "peter.txt", and there can be folder nodes named "peter" and "peter.txt".

So, to conclude, in Java there is really no difference in file handling regarding the extension.

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533680

Java doesn't understand file extensions and doesn't treat a file any differently based on its extension, or lack of extension. If Java thinks a File is a directory, then it is a directory. I suspect this is not what is happening. Can you try?

File file = new File(filename);
System.out.println('\'' + filename + "'.isDirectory() is "+file.isDirectory());
System.out.println('\'' +filename + "'.isFile() is "+file.isFile());

BTW: On Unix, a file file. is different to file which is different to FILE. AFAIK on Windows/MS-DOS they are treated as the same.

Upvotes: 1

MalteseUnderdog
MalteseUnderdog

Reputation: 2011

The extension should not make a difference. Can you post us the code you are using? And the error message please (stack trace).

Something along these lines should do the trick (taken from http://www.kodejava.org/examples/241.html)

//
// Create an instance of File for data file.
//
File file = new File("data");

try {
    //
    // Create a new Scanner object which will read the data 
    // from the file passed in. To check if there are more 
    // line to read from it we check by calling the 
    // scanner.hasNextLine() method. We then read line one 
    // by one till all line is read.
    //
    Scanner scanner = new Scanner(file);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        System.out.println(line);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

Upvotes: 0

rodion
rodion

Reputation: 15029

new File("settings") should work fine. Java does not treat files with or without extension differently.

Upvotes: 1

Related Questions