Java don't read in pictures and audio files with relative path - java

In java i programmed a small program to play audio file and sow pictures:
At first i make a final String with the path and then i made a file object.
At least i save the returned array in my "tracks" variable.
This is my code:
private static final String PATH = "../src/audio/";
private static final File FILE = new File(PATH);
tracks = liesAudioDateien(file);
private AudioClip[] liesAudioDateien (File inputFile) {
File[] dateFileArray;
AudioClip[] tracks;
dateFileArray = inputFile.listFiles();
tracks = new AudioClip[dateFileArray.length];
for (int i = 0; i < tracks.length; i++) {
if (dateFileArray[i].isFile()) {
try {
tracks[i] = Applet.newAudioClip(dateFileArray[i].toURL());
} catch (IOException ex) {
System.err.println("Oops!: -- " + ex.toString());
}
}
}
return tracks;
If I run this code, I get an error:
Exception in thread "main" java.lang.NullPointerException
at source.Sound.liesAudioDateien(Sound.java:32)
Sound.java:32:
This is tracks = new AudioClip[dateFileArray.length]; line.
If i try with an absolute path, it does work!
What i do wrong?

Change "../src/audio/" to "./src/audio/"

Your path is relative, which is resolved to be relative to the current working directory. The current working directory is not what you think it is.
Try to do this before inputFile.listFiles();
System.out.println(inputFile.getAbsolutePath());
And see what Java thinks the absolute path should be.

File.listFiles returns null if the abstract pathname does not denote a directory.
You need to make sure inputFile does denote a directory to ensure dateFileArray is not null.

Try it with File.separator in place of forward/backward slash.
ex:
String soundDir = "." + File.separator + "folderName" + File.separator;
String fileName = "sound.wav";
String filePath = soundDir+ + fileName;

Related

Java create multiple new files

I read this question here How to create a file in a directory in java?
I have a method that creates a QR Code. The method is called several times, depends on user input.
This is a code snippet:
String filePath = "/Users/Test/qrCODE.png";
int size = 250;
//tbd
String fileType = "png";
File myFile = new File(filePath);
The problem: If the user types "2" then this method will be triggered twice.
As a result, the first qrCODE.png file will be replaced with the second qrCODE.png, so the first one is lost.
How can I generate more than one qr code with different names, like qrCODE.png and qrCODE(2).png
My idea:
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Any tips?
EDIT: I solved it by using a for loop and incrementing the number in the filename in every loop step.
You can create more files eg. like follows
int totalCount = 0; //userinput
String filePath = "/Users/Test/";
String fileName= "qrCODE";
String fileType = "png";
for(int counter = 0; counter < totalCount; counter++){
int size = 250;
//tbd
File myFile = new File(filePath+fileName+counter+"."+fileType);
/*
will result into files qrCODE0.png, qrCODE1.png, etc..
created at the given location
*/
}
Btw to add check if file exists is also good point.
{...}
if(!myFile.exists()){
//file creation
myFile.createNewFile()
}else{
//file already exists
}
{...}
Your idea of solving the problem is a good one. My advice is to break up the filePath variable into a few variables in order to manipulate the file name easier. You can then introduce a fileCounter variable that will store the number of files created and use that variable to manipulate the name of the file.
int fileCounter = 1;
String basePath = "/Users/Test/";
String fileName = "qrCODE";
String fileType = ".png";
String filePath = basePath + fileName + fileType;
File myFile = new File(filePath);
You can then check if the file exists and if it does you just give a new value to the filePath variable and then create the new file
if(myFile.exists()){
filePath = basePath + fileName + "(" + ++fileCounter + ")" + fileType;
myFile = new File(filePath);
}
createFile(myFile);
And you're done!
You can check /Users/Test direcroty before create file.
String dir = "/Users/Test";
String pngFileName = "qrCode";
long count = Files.list(Paths.get(dir)) // get all files from dir
.filter(path -> path.getFileName().toString().startsWith(pngFileName)) // check how many starts with "qrCode"
.count();
pngFileName = pngFileName + "(" + count + ")";

Create directory in Java but don't throw error if it already exists [duplicate]

The condition is if the directory exists it has to create files in that specific directory without creating a new directory.
The below code only creates a file with the new directory but not for the existing directory . For example the directory name would be like "GETDIRECTION":
String PATH = "/remote/dir/server/";
String fileName = PATH.append(id).concat(getTimeStamp()).append(".txt");
String directoryName = PATH.append(this.getClassName());
File file = new File(String.valueOf(fileName));
File directory = new File(String.valueOf(directoryName));
if (!directory.exists()) {
directory.mkdir();
if (!file.exists() && !checkEnoughDiskSpace()) {
file.getParentFile().mkdir();
file.createNewFile();
}
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
Java 8+ version:
Files.createDirectories(Paths.get("/Your/Path/Here"));
The Files.createDirectories() creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists.
This code checks for the existence of the directory first and creates it if not, and creates the file afterwards. Please note that I couldn't verify some of your method calls as I don't have your complete code, so I'm assuming the calls to things like getTimeStamp() and getClassName() will work. You should also do something with the possible IOException that can be thrown when using any of the java.io.* classes - either your function that writes the files should throw this exception (and it be handled elsewhere), or you should do it in the method directly. Also, I assumed that id is of type String - I don't know as your code doesn't explicitly define it. If it is something else like an int, you should probably cast it to a String before using it in the fileName as I have done here.
Also, I replaced your append calls with concat or + as I saw appropriate.
public void writeFile(String value){
String PATH = "/remote/dir/server/";
String directoryName = PATH.concat(this.getClassName());
String fileName = id + getTimeStamp() + ".txt";
File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}
File file = new File(directoryName + "/" + fileName);
try{
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
}
catch (IOException e){
e.printStackTrace();
System.exit(-1);
}
}
You should probably not use bare path names like this if you want to run the code on Microsoft Windows - I'm not sure what it will do with the / in the filenames. For full portability, you should probably use something like File.separator to construct your paths.
Edit: According to a comment by JosefScript below, it's not necessary to test for directory existence. The directory.mkdir() call will return true if it created a directory, and false if it didn't, including the case when the directory already existed.
Trying to make this as short and simple as possible. Creates directory if it doesn't exist, and then returns the desired file:
/** Creates parent directories if necessary. Then returns file */
private static File fileWithDirectoryAssurance(String directory, String filename) {
File dir = new File(directory);
if (!dir.exists()) dir.mkdirs();
return new File(directory + "/" + filename);
}
I would suggest the following for Java8+.
/**
* Creates a File if the file does not exist, or returns a
* reference to the File if it already exists.
*/
public File createOrRetrieve(final String target) throws IOException {
final File answer;
Path path = Paths.get(target);
Path parent = path.getParent();
if(parent != null && Files.notExists(parent)) {
Files.createDirectories(path);
}
if(Files.notExists(path)) {
LOG.info("Target file \"" + target + "\" will be created.");
answer = Files.createFile(path).toFile();
} else {
LOG.info("Target file \"" + target + "\" will be retrieved.");
answer = path.toFile();
}
return answer;
}
Edit: Updated to fix bug as indicated by #Cataclysm and #Marcono1234. Thx guys:)
code:
// Create Directory if not exist then Copy a file.
public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException {
Path FROM = Paths.get(origin);
Path TO = Paths.get(destination);
File directory = new File(String.valueOf(destDir));
if (!directory.exists()) {
directory.mkdir();
}
//overwrite the destination file if it exists, and copy
// the file attributes, including the rwx permissions
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(FROM, TO, options);
}
Simple Solution using using java.nio.Path
public static Path createFileWithDir(String directory, String filename) {
File dir = new File(directory);
if (!dir.exists()) dir.mkdirs();
return Paths.get(directory + File.separatorChar + filename);
}
If you create a web based application, the better solution is to check the directory exists or not then create the file if not exist. If exists, recreate again.
private File createFile(String path, String fileName) throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(".").getFile() + path + fileName);
// Lets create the directory
try {
file.getParentFile().mkdir();
} catch (Exception err){
System.out.println("ERROR (Directory Create)" + err.getMessage());
}
// Lets create the file if we have credential
try {
file.createNewFile();
} catch (Exception err){
System.out.println("ERROR (File Create)" + err.getMessage());
}
return file;
}
A simple solution using Java 8
public void init(String multipartLocation) throws IOException {
File storageDirectory = new File(multipartLocation);
if (!storageDirectory.exists()) {
if (!storageDirectory.mkdir()) {
throw new IOException("Error creating directory.");
}
}
}
If you're using Java 8 or above, then Files.createDirectories() method works the best.

How to move folder and files?

My program uses a file database and I was wondering how to move a folder without deleting the files from within the folder. I am using java. When I press a button I would like them to move to a specified location. The code on the button looks like this:
private void uploadButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
ProjectInfo.documentTitle = fileName.getText();
ProjectInfo.moveFileLocation = fileSpecificLocation.getText();
String name = userNameText.getText();
Signup.fileToMoveTo = "C:\\CloudAurora\\" + name + "\\";
String docTtl = ProjectInfo.documentTitle;
// docTtl.renameTo(new File(Signup.fileToMoveTo));
ProjectInfo.documentTitle = fileName.getText();
ProjectInfo.moveFileLocation = fileSpecificLocation.getText();
String name = userNameText.getText();
Signup.fileToMoveTo = "C:\\CloudAurora\\" + name + "\\";
String docTtl = ProjectInfo.documentTitle;
System.out.println(ProjectInfo.documentTitle);
System.out.println(Signup.fileToMoveTo);
}
If Someone could help that would be awesome. I have looked for a way to do it but couldn't figure out how
I hope as per your case, I have mentioned the source file and destination file correctly. Below code should move the folders along with the file.
File srcFile = new File(docTtl);
File destFile = new File(Signup.fileToMoveTo);
/* Handle IOException for the below line */
Files.move(Paths.get(srcFile.getPath()), Paths.get(destFile.getPath()), StandardCopyOption.REPLACE_EXISTING);

Java - Getting file name without extension from a folder

I'm using this code to get the absolute path of files inside a folder
public void addFiles(String fileFolder){
ArrayList<String> files = new ArrayList<String>();
fileOp.getFiles(fileFolder, files);
}
But I want to get only the file name of the files (without extension). How can I do this?
i don't think such a method exists. you can get the filename and get the last index of . and truncate the content after that and get the last index of File.separator and remove contents before that.
you got your file name.
or you can use FilenameUtils from apache commons IO and use the following
FilenameUtils.removeExtension(fileName);
This code will do the work of removing the extension and printing name of file:
public static void main(String[] args) {
String path = "C:\\Users\\abc\\some";
File folder = new File(path);
File[] files = folder.listFiles();
String fileName;
int lastPeriodPos;
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
fileName = files[i].getName();
lastPeriodPos = fileName.lastIndexOf('.');
if (lastPeriodPos > 0)
fileName = fileName.substring(0, lastPeriodPos);
System.out.println("File name is " + fileName);
}
}
}
If you are ok with standard libraries then use Apache Common as it has ready-made method for that.
There's a really good way to do this - you can use FilenameUtils.removeExtension.
Also, See: How to trim a file extension from a String
String filePath = "/storage/emulated/0/Android/data/myAppPackageName/files/Pictures/JPEG_20180813_124701_-894962406.jpg"
String nameWithoutExtension = Files.getNameWithoutExtension(filePath);

file path from \ to /

I have this problem: I am choosing a file from JFileChooser and if i take a system print i get this path: C:\Users\Joakim\Desktop\dude.txt and when i want to use this link to copy this file to another location i need to have the path like this: C://Users/Joakim/Desktop/dude.txt
How can i do this?
public void upload(String username) throws RemoteException, NullPointerException{
JFileChooser chooser = new JFileChooser(getProperty + "/desktop/");
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
} try {
String fileName = chooser.getSelectedFile().getName();
System.out.println(fileName); //name of the file
File selectedFile = chooser.getSelectedFile();
System.out.println(selectedFile); //path of the file
//File path= selectedFile.replaceAll('/','/');
String serverDirectory = ("C://Users/Joakim/Dropbox/Project RMI/SERVER/");
byte[] filedata = cf.downloadFile(selectedFile);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(serverDirectory + fileName));
output.write(filedata, 0, filedata.length);
output.flush();
output.close();
} catch (Exception e) {
System.err.println("FileServer exception: " + e.getMessage());
e.printStackTrace();
}
}
Thanks in Advance :)
Edit: So this did not work out as i planed. I wanted to change the path to C://Users/Joakim/Desktop/dude.txt but thats not enough. I need to have //C://Users/Joakim/Desktop/dude.txt. The problem i have now is to get that and still use it as a File. I did test out
File newFil = new File("//" + selectedFile);
byte[] filedata = cf.downloadFile(nyFil);
This do not work for me. I still get out C://Users/Joakim/Desktop/dude.txt
Do someone have a tip or two? :)
You should really be using the system properties file.separator:
Character that separates components of a file path. This is "/" on
UNIX and "\" on Windows.
String fileSeparator = System.getProperty("file.separator");
You can also access the file separator as File.separator
Consider breaking up your path to incorporate the use of this property in lieu of forward or backward slashes.
It's simple, try this :
String first = "C:\\Mine\\Java";
String second = first.replace("\\", "/");
second = second.replaceFirst("/", "//");
System.out.println(second);
OUTPUT :
Hope this might help in some way.
Regards
This should work: C:\Users use double \
Try with this
/**
* Prepare dropbox path from the path.
*
* #param path
* that is to be formated.
* #return
* Return dropbox formated path.
*/
public static String createDropboxPathFormat(String path) {
// Replaced all \ with / of the path.
String dropboxPath = path.replaceAll("[\\\\]", "/");
// Finally replaced all // with /
dropboxPath = dropboxPath.replaceAll("[//]", "/");
return dropboxPath;
}

Categories