如何在避免空指针异常的同时成功 return mp3 文件的元数据
How to successfully return the metadata off of an mp3 file while avoiding a null pointer exception
当我尝试 运行 获取元数据并从 mp3 文件打印它的程序时,我在项目中返回 "Exception in thread "main" java.lang.NullPointerException。mp3MetaData.main(musicdj.java:18)”。为此 class 你需要 jid3lib jar。如何避免此异常,是否需要通过底部的标签传递任何变量?
package 1234;
import java.io.File;
import java.io.IOException;
import org.farng.mp3.MP3File;
import org.farng.mp3.TagException;
import org.farng.mp3.id3.ID3v1;
public class mp3MetaData {
public static void main(String[] args) throws IOException, TagException {
// TODO Auto-generated method stub
File sourceFile = new File("/Users/JohnSmith/Desktop/MusicTester/1234.mp3");
MP3File mp3file = new MP3File(sourceFile);
ID3v1 tag = mp3file.getID3v1Tag();
System.out.println(tag.getAlbum());
System.out.println(tag.getAlbumTitle());
System.out.println(tag.getTitle());
System.out.println(tag.getComment());
}
}
任何帮助将不胜感激。
您的 MP3 文件可能不包含 ID3 标签。所以在使用之前检查 tag
是否是 null
。像这样:
public static void main(String[] args) throws IOException, TagException
{
File sourceFile = new File("/Users/JohnSmith/Desktop/MusicTester/1234.mp3");
final MP3File mp3file = new MP3File(sourceFile);
final ID3v1 tag = mp3file.getID3v1Tag();
if (null == tag)
{
System.out.println("No ID3 tag found!");
}
else
{
System.out.println(tag.getAlbum());
System.out.println(tag.getAlbumTitle());
System.out.println(tag.getTitle());
System.out.println(tag.getComment());
}
}
当我尝试 运行 获取元数据并从 mp3 文件打印它的程序时,我在项目中返回 "Exception in thread "main" java.lang.NullPointerException。mp3MetaData.main(musicdj.java:18)”。为此 class 你需要 jid3lib jar。如何避免此异常,是否需要通过底部的标签传递任何变量?
package 1234;
import java.io.File;
import java.io.IOException;
import org.farng.mp3.MP3File;
import org.farng.mp3.TagException;
import org.farng.mp3.id3.ID3v1;
public class mp3MetaData {
public static void main(String[] args) throws IOException, TagException {
// TODO Auto-generated method stub
File sourceFile = new File("/Users/JohnSmith/Desktop/MusicTester/1234.mp3");
MP3File mp3file = new MP3File(sourceFile);
ID3v1 tag = mp3file.getID3v1Tag();
System.out.println(tag.getAlbum());
System.out.println(tag.getAlbumTitle());
System.out.println(tag.getTitle());
System.out.println(tag.getComment());
}
}
任何帮助将不胜感激。
您的 MP3 文件可能不包含 ID3 标签。所以在使用之前检查 tag
是否是 null
。像这样:
public static void main(String[] args) throws IOException, TagException
{
File sourceFile = new File("/Users/JohnSmith/Desktop/MusicTester/1234.mp3");
final MP3File mp3file = new MP3File(sourceFile);
final ID3v1 tag = mp3file.getID3v1Tag();
if (null == tag)
{
System.out.println("No ID3 tag found!");
}
else
{
System.out.println(tag.getAlbum());
System.out.println(tag.getAlbumTitle());
System.out.println(tag.getTitle());
System.out.println(tag.getComment());
}
}