How to read from a file that has no extension in Java? - 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

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

Related

No matter what I do, I can't get Java to recognize the filepath for a text file

I've been trying to set up a Scanner to use a File as an input, but it doesn't seem to recognize the filepath. The file exists in the same folder as my .java files.
File errorList = new File("Errors.txt");
Scanner errorIn = new Scanner(errorList);
This results in a FileNotFoundException.
What am I doing wrong, and how can I fix this?
One other approach you could try is, execute the below code in your eclipse (from any of your class), and see where the hello.txt is created, so you get an idea of where Java is looking for the file.
new File("hello.txt").createNewFile();
Then you could either put your Errors.txt in that location or provide the corresponding relative location.

In Java, how do I find the proper path to open a txt file that's name is provided as a command line arguement?

I'm working on a program that is supposed to take two files as command line arguments, open the files, and read data from the files to make a data structure.
So far, I have been able to make the structure using File() to open the files and Scanner to read the data. The problem is that I have been providing a specific path to the call for File like this
File f1 = new File("F:/MinSpan/resources/cities.txt");
Scanner sc1 = new Scanner(f1);
I don't think this is going to work for the person who tries to run this program, because I have provided the path for where my specific txt files are located - they're on my flash drive (F) and in some folders. Is there a way I can program this to pass some kind of args[] value in for File() based on the cmd arguement the user has provided?
I have already tried just doing new File(args[2]) , and it can't find the file because there is no path.
The reason for that is because, if you are passing in only two paths, args[2] wont return anything, because args[] starts at 0. So you'd want to use:
new File(args[0]);
new File(args[1]);
Does that make sense?
If you're going for something like java -jar program.jar FILE, then have the program check for the String in args[] at index 0.
Then, construct your file. Check if the file exists (in java.io, it's File.exists()) and return an error message to the user if it's wrong.

Where i Can find text file created by servlet in Eclipse

This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.

tempfile gives wrong absolutepath after renameto

I'm changing contents of a file, therefore I read a file line by line, replace what I want and write line by line to a tempfiles. When the whole file is processed, I delete the original file, and rename the tempfile to the original filename.
like this
File orginialFile = new File("C:\\java\\workspace\\original.xml");
File tempFile = File.createTempFile("tempfile", ".tmp", new File(C:\\java\\workspace\\"));
while ((str_String = reader.readLine()) != null) {
//read lines and replace and write lines
}
orginialFile .delete();
tempFile.renameTo(new File("C:\\java\\workspace\\original.xml"));
After this is done, I request the absolutepath (tempFile.getAbsolutePath();) of the temp file. But this gives me
c:\java\workspace\tempfile3729727953777802965.tmp (the number changes every run of the program) in stead of c:\java\workspace\original.xml
How come?
I debugged it and just before the moment that I request the absolutepath, I checked in c:\java\workspace (windows explorer) and there is no tempfile. Only original file.
So the process runs correctly, I just wanted to know why it is not showing the renamed absolutepath. (I would use it for logging)
Thx
In the documentation of java.io.File, before the Interoperability with java.nio.file package:
Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.
So it won't show the renamed absolutepath.
There is a missing reader.close() before the delete. Likely edited out for us. Also you can do:
tempFile.renameTo(originialFile);
Have you checked the return value from renameTo()? I suspect it to be false.
Also pay attention to the api documentation. It states that a lot of things can go wrong - e.g. moving between file systems.
You might be better off with Files.move

Java Method Can't Pick Up Files

I'm writing a Java program that has a working drag and drop GUI for files. All of the files that are dragged in the DnD GUI are put into an String array that holds the file names. I have a method that loops through the array and strips the path to leave only the filenames and then sends the filename (for the Scanner) and the desired output filename (for the PrintWriter) to this method at the end of each loop:
public void fileGenerator(String in, String out) {
try {
String current_directory = System.getProperty("user.dir");
Scanner input = new Scanner(new FileReader(current_directory+"/"+in));
PrintWriter output = new PrintWriter(current_directory+"/"+out);
while(input.hasNext()) {
String line = input.nextLine();
output.println(line);
} output.close();
input.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
The code is not working, it does not produce the output file. I am getting a "No such file or directory" error with the full path... I have tested it in terminal, it is the correct path. Any input is appreciated.
I should note that all of the Java source files, classes, and input files are in the same directory.
Thanks!
First problem I see is that you ignore the exception, so you don't know if it opens the input file successfully. Don't ignore exceptions, even if you don't know what to do with them, print them so you could analyze your problems later on.
Second, debug the code, see where it gets an exception, if at all, see what are the values at each step.
Third, to answer your question, assuming you work with Eclipse, if you refer to the file with relative path, the working directory is not the source / class folder, but the project folder.

Categories