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).
Related
This is a chunk of data I'd like to access by a method.
I'm doing the following to read my file:
String fileName = "file.txt"
InputStream inputStream = new FileInputStream(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
My file.txt is in the same package, but I still get FileNotFoundException.
I didn't use a path url to point to the file because I thought since this it going to be an android application, hard-coding the path might not work when deployed... Please correct me if I am wrong. Thanks bunch!
This shows how to do that. https://stackoverflow.com/a/14377185/2801237
Also the 'package' your class is in has nothing to do with the 'path' where the file is being executed from. (two different concepts, 'package' = folder hierarchy of java source code files), 'path' = location on a filesystem of a specific file, your APK is being 'executed' in a particular place, and the location it writes a file is associated with that (I actually don't know where 'offhand' it writes by default, because I always get cache dir, or sd card root, etc.)
You may use:
InputStream inputStream = this.getClass().getResourceAsStream(fileName);
I would like to know how I can open and display a .txt in a Java application . The .txt is associated with the application and when you click on it , the application opens, but the file does not get to be shown if not by passing a fixed route.
I've got to show it but only if the .txt file is in the same directory as the jar file and run the application only if directly . The direct access from the .txt opens the application but nothing more .
I have this code , you see the path step them directly . I want you to take from the .txt has been clicked .
FileReader f = new FileReader("archivo.txt");
BufferedReader b = new BufferedReader(f);
String linea_cliente = b.readLine();
StringTokenizer datos_cliente = new StringTokenizer(linea_cliente,";");
while(datos_cliente.hasMoreTokens()){
pedido.setText(datos_cliente.nextToken());
id_cliente.setText(datos_cliente.nextToken());
nom_cli.setText(datos_cliente.nextToken());
dir_cli.setText(datos_cliente.nextToken());
cp_cli.setText(datos_cliente.nextToken());
loc_cli.setText(datos_cliente.nextToken());
prov_cli.setText(datos_cliente.nextToken());
pais_cli.setText(datos_cliente.nextToken());
obs_cli.setText(datos_cliente.nextToken());
}
Sorry for my bad English . Thank You ;)
FileReader f = new FileReader("archivo.txt");
Implies that archivo.txt is a relative path. Relative meaning in relation to the current executable. It is an implied .\archivo.txt
You can place it in a sub directory and use a relative path again like .\myfiles\textfiles\archivo.txt where .\ is the location of your jar.
If you want to input many different text files and you don't know where they will be then you can use arguments. From the command line it would look like:
> java jar myproj.jar C:\test\foo\archivo.txt
And to access it in main() use:
String filePath = args[0]
FileReader f = new FileReader(filePath);
If you want it to be portable accross many systems you'll need to take advantage of environment variables to get your base path and then attach the route to your .txt file to the base.
Sorry, it was a little unclear what you were asking for so I covered a few common cases, let me know if you need clarification.
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).
I'm making a game that saves information into a binary file so that I can start at the point I left the game on the next use.
My problem is that it works fine on my PC because I chose a path that already existed to save the file, but once I run the game on another PC, I got an error saying the path of the file is invalid (because i doesn't exist yet, obviously).
Basically I'm using the File class to create the file and then the ObjectOutputStream and ObjectInputStream to read/write info.
Sorry for the noob question, I'm still pretty new to using files.
You must first check if the directory exists and if it does not exist then you must create it.
String folderPath = System.getProperty("user.home") + System.getProperty("file.separator") + "MyFolder";
File folder = new File(folderPath);
if(!folder.exists())
{
folder.mkdirs();
}
File saveFile = new File(folderPath, "fileName.ext");
Please note that the mkdirs() method is more useful in this case instead of the mkdir() method as it will create all non existing parent folders.
Hope this helps. Good luck and have fun programming!
Cheers,
Lofty
You are looking for File mkdirs()
Which will create all the directories necessary that are named in your path.
For example:
File dirs= new File("/this/path/does/not/exist/yet");
dirs.mkdir();
File file = new File(dirs, "myFile.txt");
Take in consideration that it may fail, due to proper file permissions.
My solution has been create a subdirectory within the user's home directory (System.getProperty("user.home")), like
File f = new File(System.getProperty("user.home") + "/CtrlAltDelData");
f.mkdir();
File mySaveFile = new File (f, "save1.txt");
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();
}