I'm trying to load a .wav file into the memory, but It keep telling me that the file doesn't exists.
String filename;
public MyClass(String _filename){
filename = _filename;
}
public void run(){
InputStream in = View.class.getClassLoader().getResourceAsStream("/sounds/"+filename);
File inputFile = new File(in.toString());
if(!inputFile.exists()){
System.err.println("Wave file not found: " + in.toString());
return;
}
}
Console:
Wave file not found: java.io.FileInputStream#dd5b524
Wave file notfound: java.io.FileInputStream#570add96
The file is in the package folder. It's in
myPackage/sounds/write.wav
EDIT:
Actually I want to load the sound:
InputStream in = this.getClass().getResourceAsStream("sounds/"+filename);
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(in);
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
return;
} catch (IOException e1) {
e1.printStackTrace();
return;
}
But the console is still with error:
Exception in thread "Thread-6" Exception in thread "Thread-7"
java.lang.NullPointerException at
com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown
Source) at
javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at com.chrissman.threads.AePlayWave.run(AePlayWave.java:47)
java.lang.NullPointerException at
com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown
Source) at
javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at com.chrissman.threads.AePlayWave.run(AePlayWave.java:47)
in.toString() does not return the path used to open the stream, it returns the class name followed by the hash: java.io.FileInputStream#dd5b524.
The error is because you do not have a file named java.io.FileInputStream#dd5b524 in your current directory.
Since you got an object instead of null as in it found your file. You can not use a File object to get this file, but you have access to it via the in object. Read the contents from the stream and use it.
Resources can be looked up both with a absolute and relative path. What you currently have is an absolute path starting with /. So change it into /myPackage/sounds/write.wav. In general I prefer absolute paths as it can be quite hard to determine which package is the "current" with relative paths.
Related
I'm trying to read a short wav file into an array of bytes using Files.readAllBytes(path)
Here is the function used :
public static byte[] fileToByteArray(String name) throws IOException {
File file = new File(name);
if (!file.exists())
System.out.println("No file found");
else System.out.println("File found");
Path path = Paths.get(name);
try {
return Files.readAllBytes(path);
} catch (IOException e) {
e.printStackTrace();
throw e;
}
byte[] audio_array;
audio_array = fileToByteArray("../../speechRecognition/name.wav");
The console output is :
File found
java.io.IOException: No such file or directory
at java.base/java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.base/java.io.File.createNewFile(File.java:1026)
at Main.main(Main.java:61)
I'm sure the path is correct because when I replace the path string by an unexisting element I get a different exception.
I tried using FileInputStream but I get the same result.
I think the excecption is triggered by my operating system (linux: kde neon distribution) but I can't pinpoint the issue.
What's more annoying is that the program is running on one of my computers and not on the other one (same distribution) and yes, I doubled checked the path provided but my file structure is the same on both computers.
I have a method:
try {
PrintWriter writer = new PrintWriter(new File(getResource("save.txt").toString()));
writer.println("level:" + level);
writer.println("coins:" + coins);
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
And it throws this error:
java.io.FileNotFoundException: file:/Users/lpasfiel/Desktop/Java%20Games/Jumpo/out/production/Jumpo/com/salsagames/jumpo/save.txt (No such file or directory)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
at java.io.PrintWriter.<init>(PrintWriter.java:263)
at com.salsagames.jumpo.Variables$Methods.save(Variables.java:49)
It says the error is in the line with PrintWriter writer = ... The file definitely exists. (but that shouldn't be a problem, should it?). This method has worked for .pngs in an ImageIcon, so I don't see why it would be any different. Could someone explain why this doesn't work and how to fix it?
Lets look carefully at this line:
java.io.FileNotFoundException: file:/Users/lpasfiel/Desktop/Java%20Games/Jumpo/out/production/Jumpo/com/salsagames/jumpo/save.txt (No such file or directory)
If you look at other examples of FileNotFoundException, you will notice that a typical message looks like this:
java.io.FileNotFoundException: /some/path/to/file.txt (No such file or directory)
or
java.io.FileNotFoundException: dir/file.txt (No such file or directory)
In short, a typical "file not found" message starts with an absolute or relative file pathname. But in your example, the message shows a "file:" URL.
I think that that is the problem. I think that you have created a File using a URL string rather than a pathname. The File constructor doesn't check this1, but when you attempt to instantiate the FileWriter, the OS complains that it cannot find a file with that pathname.
(The clues are that the supposed pathname starts with "file:", and that it also includes a %-escaped space.)
Solution:
Something like one of the following ... depending on what getResource() is returning.
File file = new File(getResource("save.txt").toURI());
PrintWriter writer = new PrintWriter(file);
or
PrintWriter writer = new PrintWriter(getResource("save.txt").openStream());
1 - And it shouldn't. A URL string is actually a syntactically valid pathname. Since a File is allowed to represent a file path that doesn't exist in the file system, there would be no basis for the File constructor to reject a URL string.
As requested, this worked:
try {
PrintWriter writer = new PrintWriter(new File(getResource("save.txt").toURI()));
writer.println("level:" + level);
writer.println("coins:" + coins);
writer.close();
} catch (FileNotFoundException | URISyntaxException e) {
e.printStackTrace();
}
I've been running into issues when trying to accessing files and images in a jar file. The program works as expected before being made into a jar file. I have created a Resources folder used ClassLoader but still getting an error on command line when trying to run the jar file it works but not all the information shows.
The type has to be a File so that the databaseReader can read it.
Error message
java.io.FileNotFoundException: file:\C:\Users\Nicholas\IdeaProjects\MirrorMe\out\artifacts\MirrorMe_jar\MirrorMe.jar!\GeoLite2-City.mmdb (The filename, directory name, or volume label syntax is incorrect)
at java.io.RandomAccessFile.open0(Native Method)
at java.io.RandomAccessFile.open(Unknown Source)
at java.io.RandomAccessFile.<init>(Unknown Source)
at com.maxmind.db.BufferHolder.<init>(BufferHolder.java:19)
at com.maxmind.db.Reader.<init>(Reader.java:116)
at com.maxmind.geoip2.DatabaseReader.<init>(DatabaseReader.java:35)
at com.maxmind.geoip2.DatabaseReader.<init>(DatabaseReader.java:23)
at com.maxmind.geoip2.DatabaseReader$Builder.build(DatabaseReader.java:129)
at sample.LocateMyCity.<init>(LocateMyCity.java:60)
at sample.WeatherToday.getPersonLocationId(WeatherToday.java:102)
at sample.WeatherToday.<init>(WeatherToday.java:126)
at sample.Main.start(Main.java:37)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Unknown Source)
Full Code
public class LocateMyCity {
private String myCityLocation;
private String country;
public String getCountry() {
return country;
}
public String getmyCityLocation(){
return myCityLocation;
}
public LocateMyCity() {
try {
ClassLoader classLoader = getClass().getClassLoader();
File database = new File(classLoader.getResource("GeoLite2-City.mmdb").getFile());
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);
// This creates the DatabaseReader object, which should be reused across
// lookups.
DatabaseReader reader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName(ip);
// Replace "city" with the appropriate method for your database, e.g.,
// "country".
CityResponse response = reader.city(ipAddress);
City city = response.getCity();
System.out.println(city.getName()); // 'Minneapolis'
this.myCityLocation = city.getName();
Country country = response.getCountry();
System.out.println(country.getIsoCode()); // 'GB'
this.country = country.getIsoCode();
System.out.println(country.getName()); // 'United Kindom'
}catch (Exception e){
e.printStackTrace();
System.out.println("Tracing IP E");
}
}
}
Thanks in advance.
When your application is bundled as a jar file, the resources are no longer files but are elements in an archive (the jar file). For a desktop application, the application will typically run without extracting these elements from the archive.
If your database requires an actual file, rather than just a stream it can read from (this would particularly be the case if you needed to write to it), then you cannot use a resource in an archive and will have to use a file on the file system.
You can easily extract the resource from the archive and write its content to the local filesystem. The exact details of how you do this depend on the functionality you need. For example, if you are writing to the database as part of the application's functionality, and expect those changes to persist the next time the application is run, you would only want to extract the resource from the archive on the first run (or possibly if the user deleted the file at a later stage). Normally you would do this by placing the file in the user's home directory. You might do this, for example, with:
Path appDirectory = Paths.get(System.getProperty("user.home"), ".application-name");
Path databaseFile = appDirectory.resolve("GeoList2-City.mmdb");
if (! Files.exists(databaseFile)) {
try {
// create the app directory if it doesn't already exist:
Files.createDirectories(appDirectory);
InputSteam defaultDatabase = getClass().getClassLoader().getResourceAsStream("GeoLite2-City.mmdb");
Files.copy(defaultDatabase, databaseFile);
} catch (IOException exc) {
// handle exception here, e.g. if application can run without db,
// set flag indicating it must run in non-db mode
// otherwise this is probably a fatal exception, show message and exit...
exc.printStackTrace();
}
}
// ...
DatabaseReader reader = new DatabaseReader.Builder(databaseFile.toFile()).build();
If you wanted a new database every time you ran the application, you would probably copy to a temporary file instead, deleting the file when the application exits.
Couldn't find too much about how to read a file that isn't somewhere on the SD card or storage, but rather right there in the android project directory.
I keep getting a FileNotFoundException. This is how I declare the file,
File SPPolicy = new File("SHPR_policy");
I've gotten the same error when putting it in the src/ directory, the src/[[package]]/ directory and the main project directory, and I get this error:
java.io.FileNotFoundException: /SHPR_policy: open failed: ENOENT (No such file or directory)
Is there a certain place I have to put this file? Is it because my file doesn't have an extension (I noticed the "/" before SHPR_policy but I didn't think it would be a problem because Eclipse let me create a file without an extension)?
Save the file in raw folder and try the below code.
try
{
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.test);
byte[] b = new byte[in_s.available()];
in_s.read(b);
txtHelp.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
txtHelp.setText("errr.");
}
Use these piece of code to check if the file was already created:
File f;
f=new File("myfile");
if(!f.exists()){
f.createNewFile();
}
Also, if you want to allocate your file in the external directory you can use these code:
File newxmlfile = new File( Environment.getExternalStorageDirectory() + "/new.xml");
XmlSerializer serializer = Xml.newSerializer();
try {
newxmlfile.createNewFile();
} catch (Exception e) {
Log.e("IOException", "exception in createNewFile() method", e);
}
And, did you added the permission in the manifest to be able to manipulate files?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You should place the file in the assets folder and use this:
InputStream ims = getAssets().open("SHPR_policy");
This question already has an answer here:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file when loading wav file
(1 answer)
Closed 4 years ago.
I'm trying to add sound to my java game...
I'm playing Sultans of swing at runtime:
static String WHOOSH = "res/WHOOSH.WAV";
static String SULTANS = "res/DireStraits_SultansOfSwing.wav";
music(SULTANS, true);
And this whoosh sound when the ball hits a paddle
music(WHOOSH, false);
public void music(String path, Boolean loop) {
try {
//will go into file folder and get music file (getResource)
AudioInputStream audio = AudioSystem.getAudioInputStream(GamePanel.class.getResource(path));
Clip clip = AudioSystem.getClip();
clip.open(audio);
clip.start();
if (loop) {
clip.loop(1000);
}
}
catch (Exception e) {
System.out.println("Check: " + path + "\n");
e.printStackTrace();
}
}
Problem:
The "Whoosh" always works, but Sultans of Swing does not. Sultans gives me this "Unsupported Audio File Exception" error, which oracle docs tells me
An UnsupportedAudioFileException is an exception indicating that an operation failed because a file did not contain valid data of a recognized file type and format.
Error:
Check: res/DireStraits_SultansOfSwing.wav
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input URL at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
But you can see from these photos that they're both .wav files...
Why is it throwing that error? Is it a size issue?
Thanks!
When I've used wav files for a game, I've done something like this (I've updated it with your path):
public void endingSound() throws IOException{
ClassLoader cl = this.getClass().getClassLoader();
InputStream failSound = cl.getResourceAsStream("res/DireStraits_SultansOfSwing.wav");
if (failSound != null){
AudioStream as = new AudioStream(failSound);
AudioPlayer.player.start(as);
}
else{
System.err.println("cannot load ending sound");
}
}
In this way I assure you won't have any problems when you will export as jar. If is still doesn't work try to rename or replace that file; it may be corrupted as #MadProgrammer said.