I am new in Java, and I am trying to use tablesaw (https://jtablesaw.github.io/tablesaw/) to do some data visualization, but I get an IOException during the import of the file (see code below).
I have tried various functions and methods of tablesaw (read/readmultiple and various builder for the XlsxReaderOptions). The xls import export is not well documented (yet), but I tried to re-use the jUnit Test I saw in the github.
I have also checked the file path, and java.io.File find it. So I guess the mistake is in the code below.
Does anyone here use tablesaw and can show me the correct way to import/export excel file ? Or through another dataviz library ?
import tech.tablesaw.api.Table;
import tech.tablesaw.io.xlsx.*;
[...]
public class App
{
[...]
private static Table getTable(String FileName)
{
XlsxReader reader = new XlsxReader();
XlsxReadOptions options = XlsxReadOptions.builder(FileName).build();
Table tab = reader.read(options);
return tab;
}
The error message :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException
at com.testPack.excelRun.App.getTable(App.java:30)
at com.testPack.excelRun.App.main(App.java:22)
Thank you for any help you could provide !
You can try solved your issue with following import:
import java.io.IOException;
And handle your sub with add IOException like this:
private static Table getTable(String FileName)throws IOException{
XlsxReader reader = new XlsxReader();
XlsxReadOptions options = XlsxReadOptions.builder(FileName).build();
Table tab = reader.read(options);
return tab;
}
Also put IOException in your main
Related
i'm trying to use itext (5.5.13) in IBM i (AKA iseries, Power, long ago AS/400). It could be done embedding java code into RPG ILE procedures, or executing plain java. We use Apache POI for Excel for a while, and it works well. We are testing itext now, but some issue persist yet.
Given that, I'm trying to test itext in plain java into IBM i. I prepared a very simple example, taken from listing 1.1 of "Itext in action", and run it. It seems to work well, but nothing is generated. No pdf file results. And no error appears while running.
am i forgetting something? are there some other aspects to take in account?
here is the code:
package QOpenSys.CONSUM.Testjeu;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class test1{
public static final String filePdf = "/QOpenSys/MyFolder/Testjeu/PdfRead1.pdf";
public static void main(String[] args)
throws DocumentException, IOException
{
///QOpenSys/MyFolder/Test/WrkBookRead1.pdf
//pdfDocument = new_DocumentVoid()
Document pdfDocument = new Document();
//pdfWriter = get_PdfWriter( pdfDocument: pdfFilePath);
PdfWriter.getInstance(pdfDocument, new FileOutputStream( filePdf ));
// jItxDocumentOpen( pdfDocument );
pdfDocument.open();
//pdfParagraph = new_PdfParagraphStr( PhraseString );
Paragraph jItxParagraph = new Paragraph("Hola, pdf");
//addToDocPg = jItxDocumentAddParagraph( pdfDocument: pdfParagraph );
pdfDocument.add(jItxParagraph);
//jItxDocumentClose( pdfDocument );
pdfDocument.close();
}
}
Solved. As said before, there was a first issue: it seems java function ran well because not errors/warnings were visible at qshell. It was false: errors were sent to outq, and were available at spool file. Being reviewed, it was a simple classpath issue. It required a full day to figure out what failed locating classpath.
Now it works, and pdf is created. I ran it on qshell, declaring environment variables for java_home (three jvm are executed concurrently by several applications), for classpath, and a couple required for tracing. Classpath declares first my class and secondly itext classes. Remaining classes comes from JRE. I have a full list of classes loaded by class loader. I hope it will help to find what fails in our embedded RPG ILE call to itext.
If anyone has any experience working with Yaml (.yml extension files), I could use some assistance. I am trying to write a little program that reads .yml files from a folder I made on my desktop.
import java.io.IOException;
import java.io.InputStream;
import org.yaml.snakeyaml.Yaml
public class readYaml {
public static void main(String[] args) throws IOException {
Yaml yaml = new Yaml();
try (InputStream in = readYaml.class.getResourceAsStream("/Collections.yml")) {
Question question = yaml.loadAs(in, Question.class);
System.out.println(question);
}
}
}
EDIT
I created a resources folder in my project file in response to an error on line 8 stating "This is coming from an error I am getting from an error I am getting on line 8, stating "The import org.yaml.snakeyaml.Yaml cannot be resolved"", but now I am getting this error. I think it will be best explained in screen shots. enter image description here
and this happens on my project folder
enter image description here
I hope this makes things clearer to understand.
So I want to make a java application in eclipse which the user i will be able to import .zip files. Each .zip file will represent a cat breed. I will click on a "train" button and my program will contact IBM Watson services and create a classifier. Then from a different window, i will import random cat images and the program will show what cat breed is in the image. Everything with the SDKs is fine since I ran some examples from the official Watson site and everything ran smoothly. Problem comes when I try to create my own classifiers. The code you are about to see is also from their site. For some reason the createClassifier method won't take the CreateClassifierOptions object as an argument.
import java.io.File;
import com.ibm.watson.developer_cloud.http.ServiceCall;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognitionCallback;
import com.ibm.watson.developer_cloud.visual_recognition.v3.*;
import com.ibm.watson.developer_cloud.visual_recognition.v3.model.*;
public class TrainningClassifier{
public static void main(String[] args) {
VisualRecognition service = new VisualRecognition(
VisualRecognition.VERSION_DATE_2016_05_20
);
service.setApiKey("aca4433597018de62edafdeebceb2bdc1482496a");
CreateClassifierOptions createClassifierOptions = new CreateClassifierOptions.Builder()
.name("dogs")
.addClass("beagle", new File("./beagle.zip"))
.addClass("goldenretriever",new File("./golden-retriever.zip"))
.addClass("husky", new File("./husky.zip"))
.negativeExamples(new File("./cats.zip"))
.build();
Classifier dogs = service.createClassifier(createClassifierOptions).execute();
System.out.println(dogs); /*error is in the above line.
the createClassifier method.*/
}
}
Error: Exception in thread "main" java.lang.Error: Unresolved
compilation problem: The method createClassifier(ClassifierOptions)
in the type VisualRecognition is not applicable for the arguments
(CreateClassifierOptions)
at testVisualRec.ForAssignment.main(ForAssignment.java:31)
Any ideas?
Found the solution. For some reason eclipse wouldn't recommend this solution I had to experiment. I just added throws IOException in main method. I also put inside the main method System.out.println(new File(".").getAbsoluteFile()); to make sure the path was correct, and it was. (SDK used for this project is 4.0.0, not the newest one. SDK found here: https://github.com/watson-developer-cloud/java-sdk/releases)
I am trying to create a Java package to interface with Excel, so I am using the org.apache.poi libraries. I've found the documentation on the POI site that shows the following:
Reading and Rewriting Workbooks
(truncated)
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
When I attempt to create a Workbook object, I get errors that it doesn't know the type. The documentation above doesn't show the import statements, but if I'm reading these POI docs correctly, I should be able to import org.apache.poi.ss.usermodel.Workbook, (and it's distinctly possible that I'm wrong because I'm very new to Java) but trying all of the following import statements all result in errors for the Workbook type.
import org.apache.poi.*;
import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
I should note that I'm using Eclipse Neon for this, and the editor is not complaining that it can't find the packages, so I'm not sure where the issue lies.
Workbook wb = WorkbookFactory.create(inp);
The actual error I'm getting in the editor is that "Workbook cannot be resolved to a type", and the same error for WorkbookFactory.
So the TL;DR is that the POI docs show that Workbook is an Interface in org.apache.poi.ss.usermodel and that WorkbookFactory is a class in the same usermodel package, but I can't figure out how to import/use them correctly.
EDIT:
The build time error I receive is
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Workbook cannot be resolved to a type
WorkbookFactory cannot be resolved
at spreadsheet.conversion.ConvertXLSXtoCSV.main(ConvertXLSXtoCSV.java:31)
The message I posted before was the editor popup... I was able to take a screenshot:
EDIT: Posting the full code, because, why not. (The multiple import statements
were just trying things out, mostly in desperation.)
package spreadsheet.conversion;
import java.text.ParseException;
import org.apache.poi.*;
import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.InputStream;
public class ConvertXLSXtoCSV {
private static String inputfilename = "";
private static String outputfilename = "";
private static int debug = 0;
private static void test(String arg) {
System.out.println(arg);
}
public static void main(String[] args) throws ParseException, Exception {
if (args.length != 1) {
throw new Exception("Requires 1 parameter. Usage: ConvertXLSXtoCSV <filename>");
}
inputfilename = args[0];
if(debug==1) {
test(inputfilename);
}
InputStream inp = new FileInputStream(inputfilename);
Workbook wb = WorkbookFactory.create(inp);
}
Any help is appreciated.
As unhelpful to others as this may be, it's the solution I've come up with so I'm posting it as an answer. Many thanks for the comments about this, but I've always hated Eclipse, and decided to go with NetBeans IDE instead. It was extremely trivial to right click on Libraries, Add JAR/Folder, and select the POI jar files, and it (and the integrated Maven install) took care of the details and it worked perfectly right off the bat and resolved all library dependencies.
I believe this due to jar file corrupted ( most probably during download for the first time). Here what you can do.
You can delete all poi folder in maven repository .m2/repository/org/apache/poi then you can update maven by Right Click on the project > Maven > Update Project. Eclipse will automatically download the dependencies and auto rebuild the workspace.
im facing the same thing like yours and manage to get it clean.
Before I start, I'd like to say that I've spent 4 hours today, 6 hours yesterday and 3 hours before that researching this issue. I've read every post I can find, followed every instruction to the letter, restarted my project, reinstalled my IDE (Netbeans) and even fresh installed my OS, and I haven't found a single piece of helpful advice, so I figured I needed to ask for help.
AND YES, I HAVE PUT THE FILE IN THE RIGHT LOCATION
... As a matter of fact, I've put the file in EVERY location. There's a copy in every folder inside my project and also a copy in the overall Projects folder, and also in My Documents. I've checked and changed and defaulted the root directory many times. PLEASE don't tell me to just use an exception handler. The file the program reads in is guaranteed to exist and contain something.
So here's my question:
I'm trying to input and read from a file, however, the result is always that the file can't be found. Here's an example of my code (and it really is down to this atm):
package project2;
import java.io.FileReader;
import java.io.*;
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
FileReader inputFile = new FileReader(args[0]);
}
}
Here are two of the errors I get (I also get Filenotfound errors, but I don't think I need to add that):
Exception in thread "main" java.lang.RuntimeException: Uncompilable source
code - unreported exception java.io.FileNotFoundException; must be caught or
declared to be thrown
at project2.Project2.main(Project2.java:14)
C:\Users\jarre\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1
BUILD FAILED (total time: 1 second)
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at project2.Project2.main(Project2.java:24)
C:\Users\jarre\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1
BUILD FAILED (total time: 0 seconds)
That's it. The file name comes from the arguments, and I have tried every possible variation of the name. I have tried naming the file outside of the arguments, as just the file name itself and also with an explicit file path.
Using a scanner won't let me read anything in. FileReader won't even run.
The text file has no special formatting or characters, and I've used the one I was supplied with and multiple that I hand typed just in case there was an issue with the one I was given. I have also made sure that ".txt" is never read or used twice (I keep my extensions on, anyway).
I have checked attributes and permissions of all files and the Netbeans program itself. I've also made sure that the text files were included in the project build.
I am not using any additional code right now, as I can't do anything until I'm sure that I can read in a file, and then output one as well. I also know that the text files aren't corrupt because I can read them in Python just fine, however, I have to use Java and I have to use Netbeans.
This is a new problem for me, I've always been able to read in files fine, and I've exhausted my options. I really need some help if anyone has any ideas.
The first exception (java.lang.RuntimeException: Uncompilable source
code) is thrown because the code that you have shown us is not valid java source code.
new FileReader(args[0]) is declared as throwing FileNotFoundException and according to the rules of the java language you either have to catch this exception or declare your main method as throwing this exception.
One way to fix this problem is to write your main method like this:
public static void main(String[] args) throws FileNotFoundException {
FileReader inputFile = new FileReader(args[0]);
}
It seems that you have solved this issue because the second exception (java.util.NoSuchElementException: No line found) is thrown by the Scanner.nextLine() method if you try to read past the end of the file.
Since you have not shown any code using the Scanner class it's hard to tell where to problem is in this case.
As a matter of fact, I've put the file in EVERY location. There's a copy in every folder inside my project and also a copy in the overall Projects folder, and also in My Documents.
Don't do that. You are creating a mess with files that will be hard to cleanup. If you want to know which file your program is reading then adding the following simple line tells you the exact path and filename:
System.out.println(new File(args[0]).getAbsolutePath());
Have you ever tried with a simple, minimal example like this:
package project2;
import java.io.FileReader;
import java.io.*;
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
System.out.println(new File(args[0]).getAbsolutePath());
FileReader inputFile = new FileReader(args[0]);
try (Scanner s = new Scanner(inputFile)) {
while (s.hasNextLine()) {
System.out.println(s.nextLine());
}
}
}
}
It should print out the name of your file with the complete path and then the contents of the file line by line.
I don't think Java is messing around with you a not found file is a not found file, please elaborate more in this issue by screens of files and directories you are working on.
I would like you to consider take a look at the following:
FileReader
Path of projects on Netbeans
I hope this helps may the code be with you.
This reads a file with no problem. I'll assume you're running JDK 8.
/**
* Read a file example
* User: mduffy
* Date: 4/21/2017
* Time: 7:48 AM
* #link http://stackoverflow.com/questions/43529600/java-nothing-will-read-in-this-file
*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Project2 {
public static void main(String[] args) {
if (args.length > 0) {
BufferedReader reader = null;
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(args[0]))) {
bufferedReader.lines().forEach(System.out::println);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Usage: Project2 <file>");
}
}
}
Here's the input file I used:
line1
line2
hello, michael
line 4
Here's the output I got:
java Project2 .\src\main\resources\test.txt
line1
line2
hello, michael
line 4
Process finished with exit code 0