reading editted text files scanner java - java

I am attempting to read a text file into a scanner object.
Scanner filescan = new Scanner (new File("src/specFiles/lists/Names"));
This code works fine, however I made manual changes to the text file. I made this list bigger. However those extra lines are not being read. It seems that the old file is still being read despite new saved changes. Any thoughts?

Check the file location you are reading and update the correct one...
File f = new File("src/specFiles/lists/Names");
System.out.println(f.getAbsolutePath());
This will print the exact location of the file read by Scanner...

If you are using Maven, resources will be read from /target. If you update a resource you will need to run mvn package to update the resource in /target.

Related

Java Scanner can't read from only File Name

I'm making a Java program to read some scores from a .csv file and calculate the average of those scores. To read from the file, I'm using the Scanner Class.
First, I create a scanner to read from my file:
Scanner scanner = new Scanner(new File("TempFile.csv"));
I expected this to work, but it returns a FileNotFoundException. So, I replaced TempFile.csv with the file's absolute file name.
Scanner scanner = new Scanner(new File(C:\\Users\....));
This gave me the result I wanted, and I was able to parse the file. I'm new to Java, but I know that it's bad practice to use the absolute file name.
How can I use only the short file name?
Scanner scanner = new Scanner(new File (new File("TempFile.csv").getAbsolutePath()));
Use above.
"TempFile.csv" is a relative path. It's relative to the working directory of your java program. This directory is the value of the System property "user.dir". The following line of code gives you that value...
String workingDirectory = System.getProperty("user.dir");
Hence if you are getting FileNotFoundException, it probably means file "TempFile.csv" is not located in the working directory of your java program.
By the way, since java 8, class java.nio.file.Files contains method readAllLines. So if file "TempFile.csv" is not too big, readAllLines may be a simpler alternative to class Scanner. Note though that you still need to provide the correct path to the file when calling that method.

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.

How to rename file forth and back in java

I want to rename a file name xxx.docx to xxx.docx.zip then rename it back to xxx.docx in Java.
Here is my code.
File file = new File(path);
File file2 = new File(path+".zip");
file.renameTo(file2);
File file3 = new File(file.getPath());
file2.renameTo(file3);
It won't work. Thank you.
Edit : The problem is I forgot to close the doc before renaming it.
The code like that works. Most probably some other process has locked the file and made it read only. You have either opened it in word (since it is docx file) or something like that. Maybe it is in a readonly location.
The code is working though. Try with different file and you will see it is fine (I tried it).

Exporting JAR with Ressources, Audio won't play

I made a small game that requires to play background music on it, I have images, a txt file and an audio file, they all work after exporting the JAR except for the audio file.
here is the code I used to import :
The Images :
(new ImageIcon(getClass().getResource("/data/131868.jpg"))
The Text file :
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/data/dictionnaire.txt")));
The Audio file ( I included also the code to play it that I found while searching) :
File f =new File(Main.class.getResource("/data/gmu.mp3").getFile());
final Player p=Manager.createRealizedPlayer(f.toURI().toURL());
p.start();
while(true){
if(p.getMediaTime().getSeconds()==p.getDuration().getSeconds()){
p.stop();
p.setMediaTime(new Time(0));
p.start();
}
}
Basically the File Object was : File f = new File("/data/gmu.mp3") I just added modifications to make it look like the others ...
It did work in Eclipse, but not JAR.
You'd better know that: File is just the name of the file, not the file itself. Like the house number, it tells you the house's location, but is doesn't represent the house.
So, you can use it like this:
InputStream is = this.getClass().getResourceAsStream("/data/gmu.mp3");
File fi = new File(is);
Tell me the result:)
Solution
Try placing the gmu.mp3 inside the source before exporting the jar.
Why?
When you export a jar, it wraps all the fun code up that is inside the source folder. File f = new File("/data/gmu.mp3") simply points the program to that file names gmu.mp3 in the file system. If you place the gmu.mp3 inside the source folder and update the File constructor to reflect the new location, the mp3 should get wrapped up into the jar along with all the code.
Let me know how it goes -Scott
A java.io.File represents a jar-ed file as "ThePacked.jar!/path/inside/file.mp3", which makes problem when used as a File.
To read a jar-ed file's content, you can read from an InputStream given by getResourceAsStream(String filename).
or
To use the file as a real java.io.File, (what I did is to) read it from the InputStream and copy it to a location outside the jar (eg. to a temprary file).

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

Categories