java.io.UnixFileSystem.createFileExclusively error on Files.readAllBytes(path) - java

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.

Related

Java -Executable JAR- Error when Creating FileWriter : FileNotFoundException access is denied

I have a program that have a file in which I write the progress I've done, so if the program is closed I can just re-read what I already did.
So if the file doesn't exist (first time I launch the program), I create it, and after that I write in it.
This work while I work with Eclipse. But since I exported to an Executable JAR, I have an error if the file already exists ! That is, I can create the file and write in it the first time, but not if I close and re-launch the program.
Here's the code :
String donePath = "./done.txt";
try {
File doneFile = new File(donePath);
doneFile.createNewFile();
allreadyDone = new ArrayList<String>(Arrays.asList(new String(
Files.readAllBytes(Paths.get(donePath))).split("\n")));
doneFileWriter = new FileWriter(donePath, true);
} catch (IOException e1) {
e1.printStackTrace();
}
and I'm getting :
java.io.FileNotFoundException: .\done.txt (Accès refusé)
at java.base/java.io.FileOutputStream.open0(Native Method)
at java.base/java.io.FileOutputStream.open(FileOutputStream.java:292)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:235)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:156)
at java.base/java.io.FileWriter.<init>(FileWriter.java:82)
at =============.Main.main(Main.java:51)
I run your program (on Windows 10) with the extension of
printing the work already done
writing something (current time)
a finally-block that flushes and closes the doneFileWriter.
With the finally block everything is OK.
Without the finally block nothing is actually written.
I would expect "Accès refusé" if the log file is already open (by a different running instance).
Or if you run your code first with one user that owns the log file. And then use a different user for the next run, that has not write access.
You use the rather modern java.nio.Paths. So I suggest some type changes and debugging output:
Path donePath = Paths.get("./done.txt");
try {
File doneFile = donePath.toFile();
UserPrincipal owner = Files.getOwner(donePath);
String permissions = PosixFilePermissions.toString(
Files.getPosixFilePermissions(donePath));
System.out.println(
String.format("abs path:%s, owner:%s, can write:%b, permissions:%s",
doneFile.getAbsolutePath(), owner.getName(),
doneFile.canWrite(), permissions));
allreadyDone = new ArrayList<String>(Arrays.asList(new String(
Files.readAllBytes(donePath)).split("\n")));
What operating system do you use?
Which Java implementation (vendor/version)?
And what is your debug output?
You need to put the createNewFile() among an if-statement, so that if it is successfully created it goes ahead, and if it does not it simply outputs "File already exists".
try {
File myObj = new File(filename);
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}

Creating temporary file and rename to actual file

I am trying to create a temporary file and then rename it to a usable file. The temp file is getting created in %temp% but not getting renamed:-
static void writeFile() {
try {
File tempFile = File.createTempFile("TEMP_FAILED_MASTER", "");
PrintWriter pw = new PrintWriter(tempFile);
for (String record : new String[] {"a","b"}) {
pw.println(record);
}
pw.flush();
pw.close();
System.out.println(tempFile.getAbsolutePath());
File errFile = new File("C:/bar.txt");
tempFile.renameTo(errFile);
System.out.println(errFile.getAbsolutePath());
System.out.println("Check!");
} catch (Exception e) {
e.printStackTrace();
}
}
There are a few reasons why a rename can fail. The common ones are:
You don't have write permission for the source or destination directory.
The file you are renaming is open (on Windows)
You are attempting to rename across different file systems.
It can be difficult to diagnose these (and other) failure reasons if you are using File.renameTo because all you get is a boolean return value.
I recommend using Files.move instead. It can cope with moving files between file systems, and will throw an exception if the file cannot be renamed.

Directory not showing up in desktop, and file not being created?

The following program has the purpose of creating a directory,
folderforallofmyjavafiles.mkdir();
and making a file to go inside that directory,
File myfile = new File("C:\\Users\\username\\Desktop\\folderforallofmyjavafiles\\test.txt");
There are two problems though. One is that it says the directory is being created at the desktop, but when checking for the directory, it is not there. Also, when creating the file, I get the exception
ERROR: java.io.FileNotFoundException: folderforallofmyjavafiles\test.txt (The system cannot find the path specified)
Please help me resolve these issues, here is the full code:
package mypackage;
import java.io.*;
public class Createwriteaddopenread {
public static void main(String[] args) {
File folderforallofmyjavafiles = new File("C:\\Users\\username\\Desktop");
try {
folderforallofmyjavafiles.mkdir(); //Creates a directory (mkdirs makes a directory)
if (folderforallofmyjavafiles.isDirectory() == true) {
System.out.println("Folder created at " + "'" + folderforallofmyjavafiles.getPath() + "'");
}
} catch (Exception e) {
System.out.println("Not working...?");
}
File myfile = new File("C:\\Users\\username\\Desktop\\folderforallofmyjavafiles\\test.txt");
//I even tried this:
//File myfile = new File("folderforallofmyjavafiles/test.txt");
//write your name and age through the file
try {
PrintWriter output = new PrintWriter(myfile); //Going to write to myfile
//This may throw an exception, so I always need a try catch when writing to a file
output.println("myname");
output.println("myage");
output.close();
System.out.println("File created");
} catch (IOException e) {
System.out.printf("ERROR: %s\n", e); //e is the IOException
}
}
}
Thank you so much for helping me out, I really appreciate it.
:)
You're creating the Desktop folder in the C:\Users\username folder. If you check the return value of mkdir, you'd notice it's false because the folder already exists.
How would the system know that you want a folder named folderforallofmyjavafiles unless you tell it so?
So, you didn't create the folder, and then you try to create a file in the (nonexistent) folder, and Java tells you the folder doesn't exist.
Agreed that it's a bit obscure, using a FileNotFoundException, but the text does say "The system cannot find the path specified".
Update
You're probably confused about the variable name, so let me say this. The following are all the same:
File folderforallofmyjavafiles = new File("C:\\Users\\username\\Desktop");
folderforallofmyjavafiles.mkdir();
File x = new File("C:\\Users\\username\\Desktop");
x.mkdir();
File folderToCreate = new File("C:\\Users\\username\\Desktop");
folderToCreate.mkdir();
File gobbledygook = new File("C:\\Users\\username\\Desktop");
gobbledygook.mkdir();
new File("C:\\Users\\username\\Desktop").mkdir();

Java getting resource relative path

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.

Java: Error when save file in Resource after Deployment

My program has a function that read/write file from resource. This function I have tested smoothly.
For example, I write something to file, restart and loading again, I can read that data again.
But after I export to jar file, I faced problems when write file. Here is my code to write file:
URL resourceUrl = getClass().getResource("/resource/data.sav");
File file = new File(resourceUrl.toURI());
FileOutputStream output = new FileOutputStream(file);
ObjectOutputStream writer = new ObjectOutputStream( output);
When this code run, I has notice error in Command Prompt:
So, My data cannot saved. (I know it because after I restarted app, nothing changed !!!)
Please help me solve this problem.
Thanks :)
You simply can't write files into a jar file this way. The URI you get from getResource() isn't a file:/// URI, and it can't be passed to java.io.File's constructor. The only way to write a zip file is by using the classes in java.util.zip that are designed for this purpose, and those classes are designed to let you write entire jar files, not stream data to a single file inside of one. In a real installation, the user may not even have permission to write to the jar file, anyway.
You're going to need to save your data into a real file on the file system, or possibly, if it's small enough, by using the preferences API.
You need to read/write file as an input stream to read from jar file.
public static String getValue(String key)
{
String _value = null;
try
{
InputStream loadedFile = ConfigReader.class.getClassLoader().getResourceAsStream(configFileName);
if(loadedFile == null) throw new Exception("Error: Could not load the file as a stream!");
props.load(loadedFile);
}
catch(Exception ex){
try {
System.out.println(ex.getMessage());
props.load(new FileInputStream(configFileName));
} catch (FileNotFoundException e) {
ExceptionWriter.LogException(e);
} catch (IOException e) {
ExceptionWriter.LogException(e);
}
}
_value = props.getProperty(key);
if(_value == null || _value.equals("")) System.out.println("Null value supplied for key: "+key);
return _value;
}

Categories