in my eclipse when i run it, everything works fine and audio is okay, but i have problem when i create my .jar executable file. Audio file is in my package and i read it with getResourceAsStream so i just want to let you know. Here is problem..
InputStream input = getClass().getResourceAsStream("/optician/funny-doorbell.wav");
AudioInputStream audioIn;
try{
Clip clip;
audioIn = AudioSystem.getAudioInputStream(input);
clip=AudioSystem.getClip();
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException | IOException e1) {
e1.printStackTrace();
} catch (LineUnavailableException e1) {
e1.printStackTrace();
}
In this first case when i run with eclipse, it works fine, but when i run .jar executable file i get : reset/mark not supported.
Second case is everything same but :
BufferedInputStream input = (BufferedInputStream) getClass().getResourceAsStream("/optician/funny-doorbell.wav");
So everything is same, point is this that i now try with BufferedInputStream but the problem i get now is : Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: sun.new.www.protocol.jar.JarURLConnection$JarURLInputStream cannot be cast to java.io.BufferedInputStream
I tried in linux and windows but it doesn't works. Where is the problem ?
I think this question has been asked and answered before. See the accepted answer here for a detailed explanation: java.io.IOException: mark/reset not supported
That said, I believe you can fix your code by modifying your first line as follows:
InputStream input = new BufferedInputStream(getClass().getResourceAsStream("/optician/funny-doorbell.wav"));
The reason you're seeing a difference in behavior is that in Eclipse, getResourceAsStream is returning an InputStream that supports read/mark. When you run out of a jar, you're getting an implementation of InputStream that does not support read/mark (JarURLInputStream).
If you wrap the returned input stream in a new BufferedInputStream, you'll have read/mark support in the stream when you're running in a jar and your code will work everywhere.
Also, you're getting the ClassCastException because you're trying to cast the input stream returned by getResourceAsStream() to BufferedInputStream. Don't cast it; instead, wrap the returned input stream in a new BufferedInputStream() as I did in the code snippet above.
Related
I'm trying to write to a file using FileOutputStream. When the user selects what file to write to, the program tries to create a FileOutputStream using that file, to check if it works. If it does not, the user has to select a different file. If it does work, the FileOutputStream is closed.
After a file, for which a FOS can be opened, has been selected the program tries again to create another FOS, but this sometimes fails.
I know that you cannot write to a file when it is open on your computer. Could it be that the first FOS has not been "fully closed" and therefore the file is still considered open, so that the second FOS can not write to it?
In the following code, what happens is that the first creation and closing of the FOS does not throw an exception, while the second one somehow does. How can this be?
(I know the problem can be solved by simply using the first FOS and not creating a second, but I am interested in understanding why this particular code behaves the way it does.)
try {
FileOutputStream out1 = new FileOutputStream(file);
out1.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileOutputStream out2 = new FileOutputStream(file);
} catch (Exception e) {
e.printStackTrace();
}
Based on the symptoms, I surmise that you are using Windows, and the error you are getting in the second open is "file is in use".
Apparently under some circumstances, Windows does not immediately close a file when the application (in this case the JVM) closes the FileHandle:
FileStream.Close() is not closing the file handle instantly
Delay between CloseHandle function call and SMB Close request
This is not Java's doing, and I am not aware of a workaround (in Java) apart from waiting a bit and retrying.
(You could see what happens if you add a Thread.sleep(1000); before the 2nd attempt to create a FileOutputStream.)
I need to write a custom batch File renamer. I've got the bulk of it done except I can't figure out how to check if a file is already open. I'm just using the java.io.File package and there is a canWrite() method but that doesn't seem to test if the file is in use by another program. Any ideas on how I can make this work?
Using the Apache Commons IO library...
boolean isFileUnlocked = false;
try {
org.apache.commons.io.FileUtils.touch(yourFile);
isFileUnlocked = true;
} catch (IOException e) {
isFileUnlocked = false;
}
if(isFileUnlocked){
// Do stuff you need to do with a file that is NOT locked.
} else {
// Do stuff you need to do with a file that IS locked
}
(The Q&A is about how to deal with Windows "open file" locks ... not how implement this kind of locking portably.)
This whole issue is fraught with portability issues and race conditions:
You could try to use FileLock, but it is not necessarily supported for your OS and/or filesystem.
It appears that on Windows you may be unable to use FileLock if another application has opened the file in a particular way.
Even if you did manage to use FileLock or something else, you've still got the problem that something may come in and open the file between you testing the file and doing the rename.
A simpler though non-portable solution is to just try the rename (or whatever it is you are trying to do) and diagnose the return value and / or any Java exceptions that arise due to opened files.
Notes:
If you use the Files API instead of the File API you will get more information in the event of a failure.
On systems (e.g. Linux) where you are allowed to rename a locked or open file, you won't get any failure result or exceptions. The operation will just succeed. However, on such systems you generally don't need to worry if a file is already open, since the OS doesn't lock files on open.
// TO CHECK WHETHER A FILE IS OPENED
// OR NOT (not for .txt files)
// the file we want to check
String fileName = "C:\\Text.xlsx";
File file = new File(fileName);
// try to rename the file with the same name
File sameFileName = new File(fileName);
if(file.renameTo(sameFileName)){
// if the file is renamed
System.out.println("file is closed");
}else{
// if the file didnt accept the renaming operation
System.out.println("file is opened");
}
On Windows I found the answer https://stackoverflow.com/a/13706972/3014879 using
fileIsLocked = !file.renameTo(file)
most useful, as it avoids false positives when processing write protected (or readonly) files.
org.apache.commons.io.FileUtils.touch(yourFile) doesn't check if your file is open or not. Instead, it changes the timestamp of the file to the current time.
I used IOException and it works just fine:
try
{
String filePath = "C:\sheet.xlsx";
FileWriter fw = new FileWriter(filePath );
}
catch (IOException e)
{
System.out.println("File is open");
}
I don't think you'll ever get a definitive solution for this, the operating system isn't necessarily going to tell you if the file is open or not.
You might get some mileage out of java.nio.channels.FileLock, although the javadoc is loaded with caveats.
Hi I really hope this helps.
I tried all the options before and none really work on Windows. The only think that helped me accomplish this was trying to move the file. Event to the same place under an ATOMIC_MOVE. If the file is being written by another program or Java thread, this definitely will produce an Exception.
try{
Files.move(Paths.get(currentFile.getPath()),
Paths.get(currentFile.getPath()), StandardCopyOption.ATOMIC_MOVE);
// DO YOUR STUFF HERE SINCE IT IS NOT BEING WRITTEN BY ANOTHER PROGRAM
} catch (Exception e){
// DO NOT WRITE THEN SINCE THE FILE IS BEING WRITTEN BY ANOTHER PROGRAM
}
If file is in use FileOutputStream fileOutputStream = new FileOutputStream(file); returns java.io.FileNotFoundException with 'The process cannot access the file because it is being used by another process' in the exception message.
i was doing a sample about reading files. I put a txt file into project folder and wrote this code but I got the exception FileNotFound and also when I try to close dataInputStream I am getting compile error(commented out line). I think I messed up everything
String str=null;
try {
FileInputStream fileInputStream=new FileInputStream("myfile.txt");
DataInputStream dataInputStream=new DataInputStream(fileInputStream);
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(dataInputStream));
str=bufferedReader.readLine();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(str);
//dataInputStream.close();
Java is really nitpicky about relative paths, so `"myfile.txt" should probably live wherever your project is being built.
As for closing the dataInputStream, it is not in scope. Declare it outside of your try block. In any case, I'd suggest placing the actual close() call in a finally block to make sure it is always done (if the reference isn't null).
I agree with Guillermo
myfile.txt needs to be in your class path.
If you run this code in command line, it should be located in the same folder as this code executes, or same package.
as for the datainput stream it is out of scope
bufferedReader.close() must use in the end of where you close this operation..
Sams Teach Yourself Java in 24 Hours Sixth Edition by Rogers Cadenhead Chapter 20 ConfigWriter.java error
I am a Java beginner. I am going through the Java book listed in the title of this post. I am super stumped at how this cannot work. The code is supposed to create a file called program.properties and put the text in lines 10 through 12 in it.
import java.io.*;
class ConfigWriter {
String newline = System.getProperty("line.separator");
ConfigWriter() {
try {
File file = new File("program.properties");
FileOutputStream fileStream = new FileOutputStream(file);
write(fileStream, "username=max");
write(fileStream, "score=12550");
write(fileStream, "level=5");
} catch (IOException ioe) {
System.out.println("Could not write file");
}
}
void write(FileOutputStream stream, String output)
throws IOException {
output = output + newline;
byte[] data = output.getBytes();
stream.write(data, 0, data.length);
}
public static void main(String[] arguments) {
ConfigWriter cw = new ConfigWriter();
}
}
Instead it does absolutely nothing. Its completely blank. I would most appreciate any help at all with this error!
There is no error or exception in your code. The snippet actually created the file. Try testing the src by giving a test path.
File file = new File("C:\\Test\\test.txt");
The above modification created the file properly. And as was mentioned, you can use fileStream.flush(); too.
The most likely problem is that you are confused about where the file will be written.
If you write to a file using a relative pathname (like "program.properties"), Java will attempt to open / create the file in the application's "current directory".
If you run the code directly from the command prompt / shell, the current directory will be the shell's current directory ... at the point that you ran the program.
If you launch using a wrapper script, then the script could change the current directory before starting the program.
If you launch from an IDE, then the IDE determines what the current directory will be.
And so on.
To avoid this problem, use an absolute pathname.
It would also be instructive to figure out where that file was actually written. On Windows you could try using the Search tool. On Linux, the find command is a good choice; e.g.
$ sudo find / -name properties.properties | less
... and wait.
Note that flushing and closing are not necessary in this particular example. You are using a FileOutputStream which is not buffered. However, if you wanted to do that, your code would need to look like this:
File file = new File("program.properties");
try (FileOutputStream fileStream = new FileOutputStream(file)) {
write(fileStream, "username=max");
write(fileStream, "score=12550");
write(fileStream, "level=5");
fileStream.flush();
} catch (IOException ioe) {
System.out.println("Could not write file");
}
Note that the fileStream is implicitly closed because we declared it as a "resource" following the try
I just wanted to read a file line by line.
This was meant to be simple, but i just can't get it right!
String fileName = "C:/Users/Diogo/Desktop/Krs_Grafo/Graph.txt";
FileReader file = new FileReader(fileName);
BufferedReader inputStream = new BufferedReader(file);
System.out.println(inputStream.readLine());
i keep getting the error:
Exception in thread "main" java.io.FileNotFoundException: C:\Users\Diogo\Desktop\Krs_Grafo\Graph.txt (O sistema não pode encontrar o arquivo especificado)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.io.FileInputStream.<init>(FileInputStream.java:79)
at java.io.FileReader.<init>(FileReader.java:41)
at krs_grafo.Krs_Grafo.main(Krs_Grafo.java:51)
Java Result: 1
The system cant find the file, but i'm sure as hell it is there!
I'm using Netbeans 7.0 on a Windows 7.
Any suggestions?
AS SAID IN THE COMMENTS, it was searching for "Graph" and not "Graph.txt". This was from a previous execution where I tried without the extension. So, I edited it to be coherent. It still doesn't work.
The problem here is that the file name was actually "Graph.txt.txt" wich I couldn't see because the extensions were hidden.
Thanks to user "Michael Brewer-Davis" who asked in the comments for "output of cd and dir in the given directory".
Also point out that either / and \\ work just fine.
As JB Nizet points in a comment, the error message hints that the program tried to open a "Graph" file (not path and no extension), which is not compatible with the code you are showing us. Are you sure that that error message comes from running that code? Didi you try to debug it (step by step) ?
Windows 7? Perhaps you'd prefer to set up a working directory in some "nice" directory, like C:\wk\ or something like that, so that you can rule out permission problems and have nicer-shorter paths.
The suggestion of some answers about backlasshes is not relevant. Forward slashes work nice in Java in Windows. No need to worry about that.
You need to add the try catch block.
public static void main(String...args){
String fileName = "C:/Users/DY.Liu/Desktop/Krs_Grafo/Graph.txt";
try{
FileReader file = new FileReader(fileName);
BufferedReader inputStream = new BufferedReader(file);
System.out.println(inputStream.readLine());
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
}
}
I had a similar problem with a java.io.FileNotFoundException. I had downloaded a project from an e-mail, unzipped and stored on my Desktop, NOT my workspace which caused the FileNotFoundException.
To get the right path, I copied down the exact path from what was shown when I imported the project. and this fixed the problem for me.