开发者

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

开发者 https://www.devze.com 2023-02-12 03:20 出处:网络
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.

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


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.


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


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.


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消