Reading metadata of mp3 file in Java - file not found exception - java

Well, my code is as below. I'd like to know why there's always an exception. The mp3 file is in the same directory as the test.java file. What am I doing wrong? Also, how do I read mp3 files from say my Music Library : path - Libraries\Music
import java.io.IOException;
import com.mpatric.mp3agic.ID3v1;
import com.mpatric.mp3agic.InvalidDataException;
import com.mpatric.mp3agic.Mp3File;
import com.mpatric.mp3agic.UnsupportedTagException;
public class test
{
public static void main(String args[])
{
Mp3File mp3file = null;
try {
mp3file = new Mp3File("dom.mp3");
} catch (UnsupportedTagException | InvalidDataException | IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("File not found.");
}
if (mp3file.hasId3v1Tag()) {
ID3v1 id3v1Tag = mp3file.getId3v1Tag();
System.out.println("Track: " + id3v1Tag.getTrack());
System.out.println("Artist: " + id3v1Tag.getArtist());
System.out.println("Title: " + id3v1Tag.getTitle());
System.out.println("Album: " + id3v1Tag.getAlbum());
System.out.println("Year: " + id3v1Tag.getYear());
System.out.println("Genre: " + id3v1Tag.getGenre() + " (" + id3v1Tag.getGenreDescription() + ")");
System.out.println("Comment: " + id3v1Tag.getComment());
}
}
}
Exception
java.io.FileNotFoundException: File not found dom.mp3
at com.mpatric.mp3agic.FileWrapper.init(FileWrapper.java:26)
at com.mpatric.mp3agic.FileWrapper.<init>(FileWrapper.java:19)
at com.mpatric.mp3agic.Mp3File.<init>(Mp3File.java:53)
at com.mpatric.mp3agic.Mp3File.<init>(Mp3File.java:41)
at test.main(test.java:13)
File not found.
Exception in thread "main" java.lang.NullPointerException at test.main(test.java:19)
The mpatric package is 3rd party. I'm guessing that works fine.
What do you mean by "same directory as you run your java process from"? Can you give me a for instance, please?

Printing this:
System.out.println("File not found.");
is misleading, given this:
catch (UnsupportedTagException | InvalidDataException | IOException e)
You need to dump the exception (e.printStackTrace() to determine the real issue).
Your .mp3 file is in the same directory as your .java file. But that's not relevant. Is it in the same directory as where you run your java process from ? That's where it needs to be.
e.g.
$ cd /mydir
$ java com.whatever.TestJava
In the above your .mp3 file needs to be in the /mydir directory

As mentioned by #BrianAgnew, you should dump your Exception.
UPDATE
Try this and select your file you want to use:
public class Test
{
public static void main(String args[])
{
Mp3File mp3file = null;
try {
JFileChooser jfc = new JFileChooser();
int fileResult = jfc.showOpenDialog(null);
if (fileResult == JFileChooser.APPROVE_OPTION) {
String path = jfc.getSelectedFile().getPath();
mp3file = new Mp3File(path);
if (mp3file!=null && mp3file.hasId3v1Tag()) {
ID3v1 id3v1Tag = mp3file.getId3v1Tag();
System.out.println("Track: " + id3v1Tag.getTrack());
System.out.println("Artist: " + id3v1Tag.getArtist());
System.out.println("Title: " + id3v1Tag.getTitle());
System.out.println("Album: " + id3v1Tag.getAlbum());
System.out.println("Year: " + id3v1Tag.getYear());
System.out.println("Genre: " + id3v1Tag.getGenre() + "("+id3v1Tag.getGenreDescription() + ")");
System.out.println("Comment: " + id3v1Tag.getComment());
} else {
System.out.println("The mp3 file does not exists or does not have a ID3v1Tag");
}
}
} catch (UnsupportedTagException | InvalidDataException | IOException e) {
System.err.println("File not found.");
e.printStackTrace();
}
}
}

Solved it! System.out.println(System.getProperty("user.dir")); Pasted that into my code, found out the root dir. Apparently it's on the same level as the src and bin folders. Pasted the file there and it works like a charm now.
Alright, if anyone was wondering if you can change the home directory, you can't.
If you want to access another folder, you'll have to resort to directory traversal. Say your music file "Ride the Lightning.mp3" is in C:\Users\"Your Username"\Music\
Then to read that you'll have to do something like this:
mp3file = new Mp3File("../../../Music/Misc/Ride the Lightning.mp3");
Cheers to Brian and Chasmo for the helpful posts.

Related

Is it possible to delay or overwrite windows cannot find 'acrord32.exe' error message in java

I need to use both executable files of Adobe reader to open documents.
acrord32.exe for the users using adobe acrobat reader and acrobat.exe for the users using adobe acrobat pro.
I have used system parameters to get done the job.
But my problem is that whenever I use the acrobat.exe version this error message is coming.
After clicking ok then my pdf file opens from acrobat.exe.
So I just want to delay/overwrite/remove this message by using java...
Here is my code
public static void openPDF(Container container, String fileName) throws Exception, PrintException {
SystemParameterHome paramHome = (SystemParameterHome) container.getHomeForEntityBean();
try {
String pdfParameter = "PDF_COMMAND";
SystemParameterObject pdfCommand = paramHome.findByPrimaryKey(pdfParameter);
String command = pdfCommand.getStringValue();
Process proc = Runtime.getRuntime().exec(command + " \"" + fileName + "\"");
int exitVal = proc.waitFor();
if(exitVal != 0) {
System.out.println("exit value in if: "+ exitVal);
pdfParameter = "PDF_COMMAND_64";
pdfCommand = paramHome.findByPrimaryKey(pdfParameter);
command = pdfCommand.getStringValue();
Runtime.getRuntime().exec(command + " \"" + fileName + "\"");
throw new PrintException("There was an error in printing. Please contact a system administrator.");
}else {
System.out.println("exit value in else "+ exitVal);
}
}
catch (Exception e) {
e.printStackTrace();
}

Get a Modified File in Linux with Java on OpenSuse Leap?

i need an approach with Java to make the Programm know when a File in Linux has been modified. I have tried Files.getLastModifiedTime(), BasicFileAttributes and lastModified. Unfortunately this has not work.
The Scenarios
Scenario A:
an empty Textfile beeing copied from A to B Folder.
then the same empty Textfile in A beeing edited and written something like "Hello World!!!" in an Editor and then copy this file again in Folder B.
Scenario B:
an empty Textfile beeing copied from A to B Folder.
then the same empty Textfile beeing copied again in Folder B.
*In Scenario A my Java Programm identify a modified File in Folder B. I use a timestamp in (dd.MM.yyyy HH:mm:SS) to give it some Unique Identifikation when i relate this Timestamp with its filename as Strings.
*But in Scenario B my Java Programm identify this file also als modified, even though there hasnt been any changes to this Textfile, its the same and its empty in Folder B. I dont know which attribute to use in Java in order to make the programm know that this File has not been modified.(This only happened to me in Linux)
I use openSuse Leap for the Linux environment and Java openJdk 1.8 for my Programm.
As this Programm starts ill copy the 2 existing files in "/tmp/testfolder" to
"/tmp/testfolder/AFolder" with a Linux cp command.
It seems to me that openSUSE Leap doesnt save the Last modified data on its files,
because i get a new and same timestamp for values in Folder A and Folder B.
This doesnt happen in Linux Mint. Unfortunately my company uses openSuse Leap :(
My code:
package com.company;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import org.apache.commons.io.FileUtils;
public class App
{
public static void main( String[] args )
{
File textFile1 = new File("/tmp/testfolder/TextFile1.txt");
File textFile2 = new File("/tmp/testfolder/TextFile2.txt");
File textFile1CopyInA = new File("/tmp/testfolder/AFolder/TextFile1.txt");
File textFile2CopyInA = new File("/tmp/testfolder/AFolder/TextFile2.txt");
File textFile1CopyInB = new File("/tmp/testfolder/BFolder/TextFile1.txt");
File textFile2CopyInB = new File("/tmp/testfolder/BFolder/TextFile2.txt");
File bfolder = new File("/tmp/testfolder/BFolder/");
try {
System.out.println("Last Modified of File at testFolder" + textFile1.getAbsolutePath() + " :: " + Files.getLastModifiedTime(textFile1.toPath(), LinkOption.NOFOLLOW_LINKS));
System.out.println("Last Modified of File at testFolder" + textFile2.getAbsolutePath() + " :: " + Files.getLastModifiedTime(textFile2.toPath(), LinkOption.NOFOLLOW_LINKS));
BufferedWriter writer = new BufferedWriter(new FileWriter(textFile1));
String data = "Hello World!!!";
writer.write(data);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
if((textFile1CopyInA.exists())&&(textFile2CopyInA.exists())){
try {
System.out.println("Last Modified of File in A" + textFile1CopyInA.getAbsolutePath() + " :: " + Files.getLastModifiedTime(textFile1CopyInA.toPath(), LinkOption.NOFOLLOW_LINKS));
System.out.println("Last Modified of File in A" + textFile2CopyInA.getAbsolutePath() + " :: " + Files.getLastModifiedTime(textFile2CopyInA.toPath(), LinkOption.NOFOLLOW_LINKS));
FileUtils.copyFileToDirectory(textFile1CopyInA, bfolder);
FileUtils.copyFileToDirectory(textFile2CopyInA, bfolder);
} catch (IOException e) {
e.printStackTrace();
}
}
if((textFile1CopyInB.exists())&&(textFile2CopyInB.exists())){
try {
System.out.println("Last Modified of File in B " + textFile1CopyInB.getAbsolutePath() + " :: " + Files.getLastModifiedTime(textFile1CopyInB.toPath(), LinkOption.NOFOLLOW_LINKS));
System.out.println("Last Modified of File in B" + textFile2CopyInB.getAbsolutePath() + " :: " + Files.getLastModifiedTime(textFile2CopyInB.toPath(), LinkOption.NOFOLLOW_LINKS));
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Thanks a lot in Advance!!

check if a folder exist in datalake using java

I want to check if a folder exist in the datalake. If exist create a file in it and If folder doesn't exist create folder and then create a file inside the folder
File directory = new File("/Raw/TEST_1/test");
System.out.println("check if directory exist");
if (directory.exists() == false) {
client.createDirectory("/Raw/TEST_1/test");
System.out.println("Directory created.");
OutputStream stream = client.createFile("/Raw/TEST_1/test/" + FuFileName, IfExists.OVERWRITE);
} else {
System.out.println("Directory exist.");
OutputStream stream = client.createFile("/Raw/TEST_1/test" + FuFileName, IfExists.OVERWRITE);
}
} catch (ADLException ex) {
printExceptionDetails(ex);
} catch (Exception ex) {
System.out.format(" Exception: %s%n Message: %s%n", ex.getClass().getName(), ex.getMessage());
}
every time directory.exists() gives me output false even if that folder exist if not giving directory.exists()output as true and not executing else statements
If you are using Java 7 or higher, then it is recommended to use java.nio in order to access the file system.
This very simple example can tell you if a given path is existing and if it is a directory or something else:
import java.nio.file.Path;
import java.nio.file.Paths;
...
public static void main(String[] args) {
Path dirPath = Paths.get("/Raw/TEST_1/test");
if (Files.exists(dirPath)) {
System.out.println(dirPath.toAbsolutePath().toString()
+ " exists on the file system");
if (Files.isDirectory(dirPath)) {
System.out.println(dirPath.toAbsolutePath().toString()
+ " is a directory");
} else {
System.err.println(dirPath.toAbsolutePath().toString()
+ " is not a directory");
}
} else {
System.err.println(dirPath.toAbsolutePath().toString()
+ " does not exist on the file system");
}
}

Java - mkdir() not writing directory

I am trying to create a directory but it seems to fail every time? I have checked that it is not a permission issue too, I have full permission to write to that directory. Thanks in advance.
Here is the code:
private void writeTextFile(String v){
try{
String yearString = convertInteger(yearInt);
String monthString = convertInteger(month);
String fileName = refernce.getText();
File fileDir = new File("C:\\Program Files\\Sure Important\\Report Cards\\" + yearString + "\\" + monthString);
File filePath = new File(fileDir + "\\"+ fileName + ".txt");
writeDir(fileDir);
// Create file
FileWriter fstream = new FileWriter(filePath);
try (BufferedWriter out = new BufferedWriter(fstream)) {
out.write(v);
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
private void writeDir(File f){
try{
if(f.mkdir()) {
System.out.println("Directory Created");
} else {
System.out.println("Directory is not created");
}
} catch(Exception e){
e.printStackTrace();
}
}
public static String convertInteger(int i) {
return Integer.toString(i);
}
Calendar cal = new GregorianCalendar();
public int month = cal.get(Calendar.MONTH);
public int yearInt = cal.get(Calendar.YEAR);
Here is the output:
Directory is not created
Error: C:\Program Files\Sure Important\Report Cards\2012\7\4532.txt (The system cannot find the path specified)
It's possibly because File.mkdir creates the directory only if the parent directory exists.
Try using File.mkdirs which creates all the necessary directories.
Here's the code which worked for me.
private void writeDir(File f){
try{
if(f.mkdirs()) {
System.out.println("Directory Created");
} else {
System.out.println("Directory is not created");
}
} catch(Exception e){
// Demo purposes only. Do NOT do this in real code. EVER.
// It squashes exceptions ...
e.printStackTrace();
}
}
The only change I made was to change f.mkdir() to f.mkdirs() and it worked
I think that #La bla bla has nailed it, but just for completeness, here are all of the things that I can think of that could cause a call to File.mkdir() to fail:
A syntax error in the pathname; e.g. an illegal character in a file name component
The directory to contain the final directory component does not exist.
There is already something with that name.
You don't have permission to create a directory in the parent directory
You don't have permission to do a lookup in some directory on the path
The directory to be created is on a read-only file system.
The file system gave a hardware error or network related error.
(Obviously, some of these possibilities can be quickly eliminated in the context of this question ...)

Redundant use of .delete()

I am trying to create a method that renames a log file in a data collection program, but there is an IOException that is thrown (infrequently) when trying to access the log file shortly after accessing it once (for a second trace of data).
I do not know if it is because of the call to .delete() or if I have to make sure the file is closed before accessing it. I am really stuck on this one. Here is the method I am working on.
public static void renameFile(String oldName, String newName) throws IOException
{
File srcFile = new File(oldName).getAbsoluteFile();
boolean bSucceeded = false;
try
{
File destFile = new File(newName).getAbsoluteFile();
if (destFile.exists())
{
if (!destFile.delete())
{
throw new IOException(oldName + " was not successfully renamed to " + newName + ", could not perform !destFile.delete()");
}
}
if (!srcFile.renameTo(destFile))
{
throw new IOException(oldName + " was not successfully renamed to " + newName + ", could not rename source file");
}
else
{
bSucceeded = true;
}
}
finally
{
if (bSucceeded)
{
srcFile.delete();
}
}
}
The code seems Ok, but as you mentioned, you must make sure to close the file before calling this method. On Unix, this may work, but on Windows you definetly cannot rename or delete a file which has an open file descriptor.

Categories