Exception in thread "main" java.lang.IllegalAccessError: [duplicate] - java

This question already has an answer here:
Apache POI Parsing error
(1 answer)
Closed 7 years ago.
I am getting the below Exception when I am trying to read an Excel file:
Exception in thread "main" java.lang.IllegalAccessError: tried to access method org.apache.poi.util.POILogger.log(ILjava/lang/Object;)V from class org.apache.poi.openxml4j.opc.PackageRelationshipCollection
at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.parseRelationshipsPart(PackageRelationshipCollection.java:304)
at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.<init>(PackageRelationshipCollection.java:156)
at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.<init>(PackageRelationshipCollection.java:124)
at org.apache.poi.openxml4j.opc.PackagePart.loadRelationships(PackagePart.java:559)
at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:112)
at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:83)
at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:128)
at org.apache.poi.openxml4j.opc.ZipPackagePart.<init>(ZipPackagePart.java:78)
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:218)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:662)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:223)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:186)
at readAndWriteToExcel.ReadingExcel.main(ReadingExcel.java:36)
My code is:
package readAndWriteToExcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
public class ReadingExcel {
private static final Log LOG = LogFactory
.getLog(ReadingExcel.class);
public static void main(String[] args) throws Exception {
String SAMPLE_PERSON_DATA_FILE_PATH = "C:/Users/Documents/Test Data 5.xlsx";
File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
InputStream inputStream = new FileInputStream(file);
// The package open is instantaneous, as it should be.
OPCPackage pkg = null;
try {
ExcelWorkSheetRowCallbackHandler sheetRowCallbackHandler = new ExcelWorkSheetRowCallbackHandler(
new ExcelRowContentCallback() {
public void processRow(int rowNum, Map<String, String> map) {
// Do any custom row processing here, such as save
// to database
// Convert map values, as necessary, to dates or
// parse as currency, etc
System.out.println("rowNum=" + rowNum + ", map=" + map);
}
});
pkg = OPCPackage.open(inputStream);
ExcelSheetCallBack sheetCallback = new ExcelSheetCallBack() {
private int sheetNumber = 0;
public void startSheet(int sheetNum) {
this.sheetNumber = sheetNum;
System.out.println("Started processing sheet number=" + sheetNumber);
}
public void endSheet() {
System.out.println("Processing completed for sheet number=" + sheetNumber);
}
};
System.out.println("Constructor: pkg, sheetRowCallbackHandler, sheetCallback");
ExcelReader example1 = new ExcelReader(pkg,
sheetRowCallbackHandler, sheetCallback);
example1.process();
System.out.println("nConstructor: filePath, sheetRowCallbackHandler, sheetCallback");
ExcelReader example2 = new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, sheetRowCallbackHandler, sheetCallback);
example2.process();
System.out.println("nConstructor: file, sheetRowCallbackHandler, sheetCallback");
ExcelReader example3 = new ExcelReader(file,
sheetRowCallbackHandler, null);
example3.process();
} catch (RuntimeException are) {
LOG.error(are.getMessage(), are.getCause());
} catch (InvalidFormatException ife) {
LOG.error(ife.getMessage(), ife.getCause());
} catch (IOException ioe) {
LOG.error(ioe.getMessage(), ioe.getCause());
} finally {
IOUtils.closeQuietly(inputStream);
try {
if (null != pkg) {
pkg.close();
}
} catch (IOException e) {
// just ignore IO exception
}
}
}
}
Is there a simple way to read and edit an Excel file (xls and xlsx) with more than 50k records? I have searched a lot and worked with a few available codes.
But I was not successful, I keep ending up with one Exception or another.

I was getting the same error:
"Handler processing failed; nested exception is
java.lang.IllegalAccessError: tried to access method
org.apache.poi.util.POILogger.log(ILjava/lang/Object;)V from class
org.apache.poi.openxml4j.opc.PackageRelationshipCollection"
After updating maven and trying to access PackageRelationshipCollection and POILogger classes in eclipse things worked fine for me. Make sure you have all the required jars i.e poi, poi-ooxml, poi-ooxml-schemas.

Related

java.io.FileNotFoundException? Unable to ouput data from excel file to console

Output Student data to the Console
I have made the Student data into a List of Student objects, I want to output the contents of the List to the Console. I don't understand what this error means. Any clarification is much appreciated!
Exception in thread "main" java.lang.RuntimeException: java.io.FileNotFoundException: scr\main\webapp\assets\JavaWebProgramming.xlsx
at StudentMain.main(StudentMain.java:23)
Caused by: java.io.FileNotFoundException: scr\main\webapp\assets\JavaWebProgramming.xlsx
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:293)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:271)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:252)
at utility.WorkbookUtility.retrievePeopleFromWorkbook(WorkbookUtility.java:17)
at StudentMain.main(StudentMain.java:16)
Process finished with exit code 1
Here is the code I believe is causing the error
import model.Person;
import utility.WorkbookUtility;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class StudentMain {
public final static String INPUT_FILE ="scr\\main\\webapp\\assets\\JavaWebProgramming.xlsx";
public static void main(String[] args) {
final File inputFile = new File(INPUT_FILE);
try {
final List<Person> people = WorkbookUtility.retrievePeopleFromWorkbook(inputFile);
for(final Person person : people) {
System.out.println(person);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

Guava's Files.move() does it move the files or copy it

I have to move huge number of file(almost 60 MB each) from folder A to folder B. Folder B is a i/p folder for a a Spring scheduled task. it picks those files and start processing in parallel. I am using Guava's file utility methods to move the files.
Files.move(sourceFile,targetFile,Charsets.UTF_8);
I do see error in my TaskScheduler class that the file is not there to read
at org.apache.commons.io.FileUtils.openInputStream(FileUtils.java:299) ~[commons-io-2.4.jar:2.4]
at org.apache.commons.io.FileUtils.lineIterator(FileUtils.java:1856) ~[commons-io-2.4.jar:2.4]
at com.varun.processor.readFile(Processor.java:342) ~[classes/:?]
My hunch is that File is in copying and hence Spring scheduled thread couldn't acquire the lock to read it.As per Guava's doc it says its move method behave like mv command on unix but I see code as copy in guava jar.
Can anyone suggest a better way to move files on unix system from spring app Where o/p directory is i/p for another downstream process.
moving files with Guava works fine. you just have to keep trying to read the file until it succeeds.
I tested moving a file with size 525 MB and Guava moved it in less than 1 second.
see below for an example (I intentionally added a delay before moving the file, so the file processor will try to open the file before and while it was being moved) :
import com.google.common.io.ByteSource;
import com.google.common.io.Files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <dependency>
* <groupId>com.google.guava</groupId>
* <artifactId>guava</artifactId>
* <version>22.0</version>
* </dependency>
*/
public class GuavaFileMoveExample {
private static final Logger LOGGER = Logger.getLogger("GuavaFileMoveExample");
public static void main(String[] args) throws IOException, InterruptedException {
GuavaFileMoveExample a = new GuavaFileMoveExample();
a.doTheWork();
}
private void doTheWork() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(new FileMover());
executorService.submit(new FileProcessor());
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
}
}
class FileMover implements Callable<Void> {
private static final Logger LOGGER = Logger.getLogger("FileMover");
#Override
public Void call() throws Exception {
Thread.sleep(1000);
moveFile();
return null;
}
private void moveFile() {
final File sourceFile = new File("/tmp/origin/ideaIU-2016.3-no-jdk.tar.gz");
final File targetFile = new File("/tmp/destination/ideaIU-2016.3-no-jdk.tar.gz");
try {
LOGGER.log(Level.INFO, "started moving file");
Files.move(sourceFile, targetFile);
LOGGER.log(Level.INFO, "finished moving file");
} catch (IOException e) {
LOGGER.log(Level.WARNING, "ioexception while moving file ", e);
}
}
}
class FileProcessor implements Callable<Void> {
private static final Logger LOGGER = Logger.getLogger("FileProcessor");
#Override
public Void call() throws Exception {
readBinaryFile("/tmp/destination/ideaIU-2016.3-no-jdk.tar.gz");
return null;
}
private byte[] readBinaryFile(String aFileName) {
File file = new File(aFileName);
ByteSource source = Files.asByteSource(file);
byte[] result = null;
while (result == null) {
try {
LOGGER.log(Level.INFO, "started reading file");
result = source.read();
LOGGER.log(Level.INFO, "finished reading file. size: " + result.length);
} catch (FileNotFoundException e) {
// expected if file is not yet at destination
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "error reading file", e);
break;
}
}
return result;
}
}

Eclipse auto suggestions for Unhandled exception type Exception (Java / Weka)

I am trying to write a script that can batch process multiple ARFF files in Weka. However I always get the "Unhandled exception type Exception" error. Eclipse is suggestion to put try-catch statements around every line of code.
After accepting the suggestions the code runs. However it is very unreadeble code if I do it like this. Any body an idea how to fix this Unhandled exception type Exception error?
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.functions.LinearRegression;
import weka.core.Instances;
import weka.core.converters.ArffLoader.ArffReader;
import weka.classifiers.trees.RandomForest;
public class Eval{
public static Instances LoadARFF(String location){
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(location));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArffReader arff = null;
try {
arff = new ArffReader(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arff.getData();
}
public static void main(String[] args) throws Exception {
//Get all files from training path
Files.walk(Paths.get("path/to/sets/Train")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
//Get the file name of the train set.
String fileLocation = filePath.normalize().toString();
String[] tokens = fileLocation.split("[\\\\|/]");
String filename = tokens[tokens.length - 1];
System.out.println("Train file:" + filename + " found!");
//Get both the train and test set
String TrainFile = "path/to/sets/Train/"+ filename;
String TestFile = "path/to/sets/Test/"+ filename;
//Load the train set
Instances train = LoadARFF(TrainFile);
train.setClassIndex(train.numAttributes() - 1);
//Load the test set.
Instances test = LoadARFF(TestFile);
test.setClassIndex(train.numAttributes() - 1);
//train classifier
Classifier cls = new RandomForest();
cls.buildClassifier(train);
// evaluate classifier and print some statistics
Evaluation eval = null;
eval = new Evaluation(train);
eval.evaluateModel(cls, test);
System.out.println(cls);
System.out.println(eval.toSummaryString("\nResults\n======\n", false));
} //if
});//for each
}//Main
}//class
The error code is as followed:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type Exception
Unhandled exception type Exception
Unhandled exception type Exception
at Eval.main(Eval.java:60)
After accepting the Eclipse auto suggestions, the code is about two times a large as before accepting.
I would do something like...
private static void processFile(Path filePath) {
System.out.println(filePath);
//Get the file name of the train set.
String fileLocation = filePath.normalize().toString();
String[] tokens = fileLocation.split("[\\\\|/]");
String filename = tokens[tokens.length - 1];
System.out.println("Train file:" + filename + " found!");
//Get both the train and test set
String TrainFile = "path/to/sets/Train/"+ filename;
String TestFile = "path/to/sets/Test/"+ filename;
//Load the train set
Instances train = LoadARFF(TrainFile);
train.setClassIndex(train.numAttributes() - 1);
//Load the test set.
Instances test = LoadARFF(TestFile);
test.setClassIndex(train.numAttributes() - 1);
//train classifier
Classifier cls = new RandomForest();
cls.buildClassifier(train);
// evaluate classifier and print some statistics
Evaluation eval = null;
eval = new Evaluation(train);
eval.evaluateModel(cls, test);
System.out.println(cls);
System.out.println(eval.toSummaryString("\nResults\n======\n", false));
}
private static void processPath(Path path) {
if(Files.isRegularFile(path)) {
try {
processFile(path);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
public static void main(String[] args) throws Exception {
//Get all files from training path
Files.walk(Paths.get("path/to/sets/Train")).forEach(Eval::processPath);
}//Main
Remove
throws Exception
from your main. Why did you add that?!?

Making changes in the properties file of Java project

I need to make a change in .properties file in my Java project. This is later deployed as a jar and used by other Java project. But according to this, I see that we should not directly make the change instead create a new object. Where should we create that new object and how can we make sure that its changes are visible?
Yes that's correct if your properties files is inside a jar then you won't be able to directly change that properties file since its packaged and zipped up in an archive. Instead you can create/change the file placed on a drive and read it, I used "user.home" for an example which you can change it as your need, below is the code for the same:
package com.test.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PropertyFileReader {
private static final Logger LOGGER = LoggerFactory
.getLogger(PropertyFileReader.class);
private static Properties properties;
private static final String APPLICATION_PROPERTIES = "application.properties";
private static final String workingDir = System.getProperty("user.home");
private static File file = new File(workingDir, APPLICATION_PROPERTIES);
static {
properties = new Properties();
}
public static void main(String[] args) {
write("hello", "2");
System.out.println(read("hello"));
}
public static String read(final String propertyName) {
try (InputStream input = new FileInputStream(file)) {
properties.load(input);
} catch (IOException ex) {
LOGGER.error("Error occurred while reading property from file : ",
ex);
}
return properties.getProperty(propertyName);
}
public static void write(final String propertName,
final String propertyValue) {
try (OutputStream output = new FileOutputStream(file)) {
properties.setProperty(propertName, propertyValue);
properties.store(output, null);
} catch (IOException io) {
LOGGER.error("Error occurred while writing property to file : ", io);
}
}
}

How to read MP3 file tags

I want to have a program that reads metadata from an MP3 file. My program should also able to edit these metadata. What can I do?
I got to search out for some open source code. But they have code; but not simplified idea for my job they are going to do.
When I read further I found the metadata is stored in the MP3 file itself. But I am yet not able to make a full idea of my baby program.
Any help will be appreciated; with a program or very idea (like an algorithm). :)
The last 128 bytes of a mp3 file contains meta data about the mp3 file., You can write a program to read the last 128 bytes...
UPDATE:
ID3v1 Implementation
The Information is stored in the last 128 bytes of an MP3. The Tag
has got the following fields, and the offsets given here, are from
0-127.
Field Length Offsets
Tag 3 0-2
Songname 30 3-32
Artist 30 33-62
Album 30 63-92
Year 4 93-96
Comment 30 97-126
Genre 1 127
WARINING- This is just an ugly way of getting metadata and it might not actually be there because the world has moved to id3v2. id3v1 is actually obsolete. Id3v2 is more complex than this, so ideally you should use existing libraries to read id3v2 data from mp3s . Just putting this out there.
You can use apache tika Java API for meta-data parsing from MP3 such as title, album, genre, duraion, composer, artist and etc.. required jars are tika-parsers-1.4, tika-core-1.4.
Sample Program:
package com.parse.mp3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.mp3.Mp3Parser;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class AudioParser {
/**
* #param args
*/
public static void main(String[] args) {
String fileLocation = "G:/asas/album/song.mp3";
try {
InputStream input = new FileInputStream(new File(fileLocation));
ContentHandler handler = new DefaultHandler();
Metadata metadata = new Metadata();
Parser parser = new Mp3Parser();
ParseContext parseCtx = new ParseContext();
parser.parse(input, handler, metadata, parseCtx);
input.close();
// List all metadata
String[] metadataNames = metadata.names();
for(String name : metadataNames){
System.out.println(name + ": " + metadata.get(name));
}
// Retrieve the necessary info from metadata
// Names - title, xmpDM:artist etc. - mentioned below may differ based
System.out.println("----------------------------------------------");
System.out.println("Title: " + metadata.get("title"));
System.out.println("Artists: " + metadata.get("xmpDM:artist"));
System.out.println("Composer : "+metadata.get("xmpDM:composer"));
System.out.println("Genre : "+metadata.get("xmpDM:genre"));
System.out.println("Album : "+metadata.get("xmpDM:album"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
}
}
For J2ME(which is what I was struggling with), here's the code that worked for me..
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.*;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.MetaDataControl;
import javax.microedition.midlet.MIDlet;
public class MetaDataControlMIDlet extends MIDlet implements CommandListener {
private Display display = null;
private List list = new List("Message", List.IMPLICIT);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Alert alert = new Alert("Message");
private Player player = null;
public MetaDataControlMIDlet() {
display = Display.getDisplay(this);
alert.addCommand(exitCommand);
alert.setCommandListener(this);
list.addCommand(exitCommand);
list.setCommandListener(this);
//display.setCurrent(list);
}
public void startApp() {
try {
FileConnection connection = (FileConnection) Connector.open("file:///e:/breathe.mp3");
InputStream is = null;
is = connection.openInputStream();
player = Manager.createPlayer(is, "audio/mp3");
player.prefetch();
player.realize();
} catch (Exception e) {
alert.setString(e.getMessage());
display.setCurrent(alert);
e.printStackTrace();
}
if (player != null) {
MetaDataControl mControl = (MetaDataControl) player.getControl("javax.microedition.media.control.MetaDataControl");
if (mControl == null) {
alert.setString("No Meta Information");
display.setCurrent(alert);
} else {
String[] keys = mControl.getKeys();
for (int i = 0; i < keys.length; i++) {
list.append(keys[i] + " -- " + mControl.getKeyValue(keys[i]), null);
}
display.setCurrent(list);
}
}
}
public void commandAction(Command cmd, Displayable disp) {
if (cmd == exitCommand) {
notifyDestroyed();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}

Categories