I'm trying to programatically set the ID3 tags of some mp3s. After having gave up the jaudiotagger I found the MyID3 library http://www.fightingquaker.com/myid3/
I'm by no means an experienced Java programmer, but I have some knowledge of OOP.
I managed to get as far as writing a class, everything works well, except for a strange error, that I can't understand.
My class is:
import org.cmc.music.myid3.*;
import org.cmc.music.metadata.*;
import java.io.*;
import java.lang.*;
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
class lrsetid3 {
public static void main(String[] args) {
String files;
File inputfolder = new File("c:\\ID3\\input");
File[] listOfFiles = inputfolder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
// files = listOfFiles[i].getName();
}
try {
MusicMetadataSet src_set = new MyID3().read(listOfFiles[i]);
IMusicMetadata metadata = src_set.getSimplified();
String artist = metadata.getArtist();
metadata.setArtist("Bob Marley");
System.out.println(listOfFiles[i].getName());
File src = new File ("c:\\ID3\\input" + listOfFiles[i].getName());
System.out.println(listOfFiles[i].isFile());
System.out.println(listOfFiles[i].exists());
File dst = new MyID3().write(src, dst, src_set, metadata);
// System.out.println("Artist" + artist); // Display the string.
}
catch (Exception e){
e.printStackTrace();
}
}
}
And the error that I get is on the line:
File dst = new MyID3().write(src, dst, src_set, metadata);
lrsetid3.java:37: error: incompatible types
File dst = new MyID3().write(src, dst, src_set, metadata);
^
required: File
found: void
1 error
The weird part is that the printouts say that the first parameter of the write function is a File... I do not get why the compiler does not want to accept src as a File variable.
Many thanks for your help
that will return a new MyID3 object.
File dst = new MyID3();
This however, will return what the write() method returns. In this case void. (I presume)
File dst = new MyID3().write(src, dst, src_set, metadata);
To fix it, do this:
File dst = new MyID3();
dst.write(src, dst, src_set, metadata);
And of course, the same rule applies to this line:
MusicMetadataSet src_set = new MyID3().read(listOfFiles[i]);
Related
I am attempting to copy a file from inside my JAR to disk, outside the JAR file. The files that I will need to copy are default configuration files for a large-scale accounting system and are needed on the computer file system.
I have searched StackOverflow, as well as other sites (found with Google) and have read around fifty answers, which I've tried all of them. The code below is the first that has not simply blown up (with NullPointerException or FileNotFoundException), but has actually attempted to get the resource located in the JAR file.
I have my JAR file set up as follows:
com.is2300.isis
MainClass.java (actual name is crazy long and I don't want to type it out right now)
com.is2300.isis.resources
Location of the resource file I would like to copy out to disk
com.is2300.isis.utils
Location of my class ResourceExporter (below - bottom) that has the file exporting methods.
My MainClass.main() entry-point function:
public static void main(String[] args) {
// Test our 'utils.ResourceExporter.exportResource(String resourceName)
//+ function.
// Set the start point of our substring to either 5 or 9, depending upon
//+ if we are debugging (in NetBeans) or not (executing the JAR).
if ( isDebugging ) {
startPoint = 5;
} else {
startPoint = 9;
}
// First, we'll try just the name of the resource file to export.
String rsName = "nwind.conf";
try {
System.out.println(ResourceExporter.exportResource(rsName,
MainClass.class, "/home/user/tmp", startPoint));
} catch (Exception ex) {
System.err.println(ex.getCause());
System.err.println(ex.getMessage());
ex.printStackTrace(System.err);
}
// Then, we'll try it with the absolute path.
rsName = "/com/is2300/isis/resources/nwind.conf";
try {
System.out.println(ResourceExporter.exportResource(rsName,
MainClass.class, "/home/user/tmp", startPoint));
} catch (Exception ex) {
System.err.println(ex.getCause());
System.err.println(ex.getMessage());
ex.printStackTrace(System.err);
}
// Then, we'll try it with the relative path.
rsName = "../resources/nwind.conf";
try {
System.out.println(ResourceExporter.exportResource(rsName,
MainClass.class, "/home/user/tmp", startPoint));
} catch (Exception ex) {
System.err.println(ex.getCause());
System.err.println(ex.getMessage());
ex.printStackTrace(System.err);
}
// Last, we'll try it using dots instead of slashes.
rsName = "com.is2300.isis.resources.nwind.conf";
try {
System.out.println(ResourceExporter.exportResource(rsName,
MainClass.class, "/home/user/tmp", startPoint));
} catch (Exception ex) {
System.err.println(ex.getCause());
System.err.println(ex.getMessage());
ex.printStackTrace(System.err);
}
}
My ResourceExporter.exportResource() method:
public static String exportResource(String resourceName, Class cls,
String outPath, int startPoint) throws Exception {
File files = new File(cls.getResource(
cls.getResource(cls.getSimpleName() +
".class").toString().substring(
startPoint, cls.getResource(
cls.getSimpleName() + ".class").toString().lastIndexOf("/")
+ 1)) + "files");
InputStream in = new FileInputStream(files);
FileOutputStream out = new FileOutputStream(outPath +
resourceName.substring(resourceName.lastIndexOf("/")));
int readBytes;
byte[] buffer = new byte[4096];
while ( (readBytes = in.read(buffer)) > 0 )
out.write(buffer, 0, readBytes);
in.close();
out.close();
return files.getAbsolutePath();
}
With what I'm doing in public static void main(String[] args), I would expect one of the calls to the ResourceExporter.exportResource() method to actually cause the file to be copied.
However, when I step through the exportResource() method, on each call after the line:
File files = new File(cls.getResource(
cls.getResource(cls.getSimpleName() +
".class").toString().substring(
startPoint, cls.getResource(
cls.getSimpleName() + ".class").toString().lastIndexOf("/")
+ 1)) + "files");
The variable files.getCanonicalPath() call shows /home/user/Projects/ProjectName/nullfiles and I do not understand why this is, nor what this is.
#JBNizet and #AndrewThompson:
Thank you both for your comments. Especially #JBNizet! You gave me a swift kick in the head that made me look closer at what I had written and immediately saw the issue. Thank you very much for that.
The fix was this: Instead of the convoluted thing I was doing:
File files = new File(cls.getResource(
cls.getResource(cls.getSimpleName() +
".class").toString().substring(
startPoint, cls.getResource(
cls.getSimpleName() + ".class").toString().lastIndexOf("/")
+ 1)) + "files");
InputStream in = new FileInputStream(files);
FileOutputStream out = new FileOutputStream(outPath +
resourceName.substring(resourceName.lastIndexOf("/")));
Which I had written about 10 years ago and don't remember what I was thinking, I was able to simplify it to this:
InputStream in = ClassLoader.getSystemClassLoader().getSystemResourceAsStream(resourceName);
FileOutputStream out = new FileOutputStream(outPath +
resourceName.substring(resourceName.lastIndexOf("/")));
Now, the "file" (as a nod to the semantic correction by #AndrewThompson) is being located within the JAR file.
However, that was not the only change that had to be made. Where I set up the variable that is passed into the parameter resourceName was also not correct. I had it set up like so:
String rsName = "/com/is2300/isis/resources/nwind.conf";
However, the leading slash (/) was not supposed to be there. As soon as I changed the above line to:
String rsName = "com/is2300/isis/resources/nwind.conf";
everything just worked the way I expected.
Again, thanks to those two who commented. I appreciate your thoughts and assistance in getting my brain engaged.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I'm totally new in this world. I want to make a simple file move program. It works fine with only 1 file and until I add the new code for multiple files move. But I wanted more and I added multiple file selection to JFileChooser. To do the move of files I search around the web and found some users that asked for something similar to it. I tried to put it in my code but I've obtained an Error like this:
Exception in thread "main" java.lang.NullPointerException
at jfile.main(jfile.java:27)
Line 27 is: for (int i = 0; i < files.length; i++) {
This is the code, thanks you and sorry for my bad English.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import javax.swing.JFileChooser;
import org.apache.commons.io.FileUtils;
public class jfile {
public static void main (String[] args) throws IOException{
System.out.println("Creado por: MarcosCT7");
if (new File(System.getProperty("user.home"), "\\AppData\\Roaming\\.minecraft\\mods").exists());{
System.out.println("Seleccione el mod a instalar:");
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setMultiSelectionEnabled(true);
int returnVal = chooser.showOpenDialog(chooser);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("Se está instalando " + chooser.getSelectedFile().getName());
File fuente = new File(chooser.getSelectedFile().getAbsolutePath());
File destino = new File(System.getProperty("user.home"), "\\AppData\\Roaming\\.minecraft\\mods");
File[] files = fuente.listFiles(); //thats new added
for (int i = 0; i < files.length; i++) {
File destFile = new File(destino.getAbsolutePath()+File.separator+files[i].getName().replace(",", "")
.replace("[", "")
.replace("]", "")
.replace(" ", "")); //until here its new added
FileUtils.moveFileToDirectory(files[i], destFile, true); //changed to multiple move, before it was: FileUtils.moveFileToDirectory(fuente, destino, true);
}
}
else {
if(returnVal == JFileChooser.CANCEL_OPTION) {
System.out.println("No se ha seleccionado ningun mod. Adios.");
}
}
}
}
}
NullPointerException means that the variable doesn't hold any reference to a object. What I mean by reference is, For ex:
String path="";
File f=new File(path);
if(f.exists()) {
// do something
}
f is a variable of type File which holds a reference to a object File defined by path
and now you can use variable f just like any other variable call methods on that variable etc.
Another example
File f;
if(f.exists()) {
// do something
}
Now you will get NullPointerException in line if(f.exists()) because f doesn't hold any reference.
In JAVA new keyword is used to assign new reference. JVM will take care of all the low level details. It is similar to pointers in c and c++. In JAVA you don't have to explicitly delete the objects. JVM garbage collector will take care of these things. Java is object oriented language
Do read and understand OOP comcepts
Before you iterate through files using the loop, check using an if statement:
if(files==null){
System.out.println("Files not found");
}
else{
for (int i = 0; i < files.length; i++) {
File destFile = new File(destino.getAbsolutePath()+File.separator+files[i].getName().replace(",", "")
.replace("[", "")
.replace("]", "")
.replace(" ", "")); //until here its new added
FileUtils.moveFileToDirectory(files[i], destFile, true); //changed to multiple move, before it was: FileUtils.moveFileToDirectory(fuente, destino, true);
}
}
I'm trying to make the program to read QR codes, however when my code runs I am getting an exception javax.imageio.IIOException: Can't read input file. The image is in the src directory. Could someone please help me to find the problem in my code...
public class BarcodeSample {
public static void main(String[] args) {
Reader reader = new MultiFormatReader();
try {
BufferedImage image = ImageIO.read(new File("src/img.png"));
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = reader.decode(bitmap);
BarcodeFormat format = result.getBarcodeFormat();
String text = result.getText();
ResultPoint[] points = result.getResultPoints();
for (int i=0; i < points.length; i++) {
System.out.println(" Point[" + i + "] = " + points[i]);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
First, use File.separator instead of '/' as it places the right separator according to the OS it is running on.
Now the problem is with src/img.png. I suggest you put your images outside the src directory as this directory is used for code (not a must).
I do not know on which IDE you run it but make sure your workspace current directory is set to your project root directory so src/img.png will be found (assuming src is under you root current directory), otherwise you will get the file not found exception
How do I get the number of slides in a .ppt file using java. To access the .ppt we require the Apache POI API - especially the Slide[] class.
I'm using the method getSlideNumber() from here to retrieve the page number but I'm still getting an error. I would like to know how to get the slide numbers.
public final class count {
public static void main(String args[]) throws Exception {
File file= new File("C:/Users/THIYAGARAJAN/Desktop/ppt52.ppt");
FileInputStream is = new FileInputStream(file);
SlideShow ppt = new SlideShow(is);
is.close();
Slide[] slide = ppt.getSlides();
System.out.println(slide.length);
for (int i = 0; i < slide.length; i++) {
String title = slide[i].getTitle();
System.out.println("Rendering slide "
+ slide[i].getSlideNumber()
+ (title == null ? "" : ": " + title));
}
}
}
Is this code correct?
Edit: Here's the error I get in my console:
Exception in thread "main" java.lang.NoSuchFieldError: filesystem
at org.apache.poi.hslf.HSLFSlideShow.getPOIFSFileSystem(HSLFSlideShow.java:79)
at org.apache.poi.hslf.EncryptedSlideShow.checkIfEncrypted(EncryptedSlideShow.java:51)
at org.apache.poi.hslf.HSLFSlideShow.<init>(HSLFSlideShow.java:141)
at org.apache.poi.hslf.HSLFSlideShow.<init>(HSLFSlideShow.java:115)
at org.apache.poi.hslf.HSLFSlideShow.<init>(HSLFSlideShow.java:103)
at org.apache.poi.hslf.usermodel.SlideShow.<init>(SlideShow.java:121)
at count.count.main(count.java:22)
have you tried
int getSlideCount()
its in the documentation..
The exception you have posted is almost straight out of the POI FAQ:
My code uses some new feature, compiles fine but fails when live with a "MethodNotFoundException" or "IncompatibleClassChangeError
You almost certainly have an older version of POI on your classpath. Quite a few runtimes and other packages will ship an older version of POI, so this is an easy problem to hit without your realising.
The best way to identify the offending earlier jar file is with a few lines of java. These will load one of the core POI classes, and report where it came from.
ClassLoader classloader =
org.apache.poi.poifs.filesystem.POIFSFileSystem.class.getClassLoader();
URL res = classloader.getResource(
"org/apache/poi/poifs/filesystem/POIFSFileSystem.class");
String path = res.getPath();
System.out.println("Core POI came from " + path);
Recently I wanted to count the number of slides I too study for my exam. The problem is very similar to your, even though your problem is 3 years old someone might find it useful.
I give my program a path it then gets all the ppt's in that folder and uses the method getNoOfSlides to count all the slides.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
public final class count {
public static int total=0;
public static void main(String args[]) throws Exception {
File files = new File("F:/Dropbox/KFUPM/Sem 151/IAS/IAS final");
searchInTextFiles(files);
System.out.println("Total Slides in IAS are: ");
System.out.println(total);
}
public static void getNoOfSlides(String path) throws IOException
{
File file = new File(path);
System.out.println(path);
FileInputStream is = new FileInputStream(file);
XMLSlideShow pps = new XMLSlideShow(is);
is.close();
List<XSLFSlide> slides = pps.getSlides();
total+= slides.size();
System.out.println(slides.size());
// System.out.println(slides.size());
}
public static void searchInTextFiles(File dir) throws IOException {
File[] a = dir.listFiles();
for (File f : a) {
if (f.isDirectory()) {
searchInTextFiles(f);
} else if (f.getName().endsWith(".pptx")) {
String path= f.getAbsolutePath();
getNoOfSlides(path);
}
}
}
}
This is my java file :
import java.io.File;
import java.lang.String;
public class ListFiles {
public static void main(String[] args) {
// Directory path here
String path = "D:/xmlfiles/";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
System.out.println(files);
}
}
}
}
This is my JS file :
function display(){
el = document.getElementById("text");
el.addEventListener("oncommand", display, true);
//loading Encryption Class
//alert('hffffi');
var myClass = cl.loadClass('ListFiles'); // use the same loader from above
var myObj = myClass.newInstance();
// Pass whatever arguments you need (they'll be auto-converted to Java form, taking into account the LiveConnect conversion rules)
var Files = myObj.String;
alert('karthik it works'+Files);
document.getElementById("text").value=Files;
}
Explanation :
I'm trying to get the ouptput string of java into my JS. I'm able to connect JAVA with JS using Live connect in XUL Firefox.
The problem right now, how can display the output of java in my JS file.
Thanks guys.
If I understand you correctly, var Files = myObj.String; is supposed to return the output of the Java program?!
I dunno that much about LiveConnect, but I'd more expect the ListFiles class to have a method that returns the list. Currently it is only read into a local variable (and main() would not be called automatically in the LiveConnect setup anyway).
So how about something like:
public class ListFiles {
public:
String getFiles() {
String result = "";
// [iterate over the files and add their names to result]
return result;
}
}
And in the JS code:
var Files = myObj.getFiles();
instead of
var Files = myObj.String;