I'm designing a form using swing.If report button was clicked in my form it have to open the predefined format excel sheet from my D drive.What code have to write in button action listener ??
Thanks ..
I'd recommend looking at the Desktop class in awt. There's a method here that should help you.
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class OpenFile {
public static void main(String[] args) {
File file = new File("c:\\appNominalJournalFix.txt");
try {
Desktop.getDesktop().open(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can use Runtime class to open the excel using the default program in Windows
String filePath = "D:\\test.xls";
Process p =
Runtime.getRuntime()
.exec("rundll32 url.dll,FileProtocolHandler " + filePath);
You can also use Desktop API as below.
String filePath = "D:\\test.xls";
Desktop dt = Desktop.getDesktop();
dt.open(new File(filePath));
Related
So I created a message console. And used append to display messages and it works perfectly by running java -jar JavaProgram, however when I double click on it the application runs and I see the JFrame but nothing is displayed. The text that I did append is not present.
By the way, double clicking it on windows does display the message output but on my linux system nothing is displayed.
I'm running the same version of java on each machine.
Code Below:
package pdfCounter;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class App {
public static JTextArea textComponent;
public static int count;
public static void main(String args[]) {
try {
JFrame somePanel = new JFrame();
somePanel.add(new JLabel(" Message Console"), BorderLayout.NORTH);
textComponent = new JTextArea(5, 10);
somePanel.setVisible(true);
somePanel.setSize(900, 300);
somePanel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
somePanel.add(new JScrollPane(textComponent));
pdfCounter.MessageConsole mc = new pdfCounter.MessageConsole(textComponent);
mc.redirectOut(null, System.out);
mc.redirectErr(Color.RED, null);
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
File root = new File(s);
count = 0;
boolean recursive = true;
Collection files = FileUtils.listFiles(root, null, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext(); ) {
try {
File file = (File) iterator.next();
if (file.getName().endsWith(".pdf")) {
String absoluteFile = file.getAbsolutePath();
append(absoluteFile);
PDDocument doc = PDDocument.load(new File(file.getAbsolutePath()));
count = doc.getNumberOfPages() + count;
doc.close();
}
} catch (Exception e) {
continue;
}
}
}
catch(Exception e) {
e.printStackTrace();
}
try (PrintStream out = new PrintStream(new FileOutputStream("NumberOfPages.txt"))) {
out.print(count);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void append(String absolutePath) {
textComponent.append(absolutePath + "\n");
}
}
when it gets to the `append(absoluteFile); part thats where the problem lies as it only appends on windows not linux.
UPDATE: I figured that opening it from a different file manager with double click, makes it work. With Nautilus is does not open, even when i choose to run it with java 8 or 9. Opening it with thunar(Different file manager) makes it work no problem with double clicking it. Both are set to run with java 9. I think it has something to do with folder permissions because if i run nautilus as root user, it works when double clicking.
I have been creating a program that writes and run java classes. So far I have been able to write a "Runable.java" class but not able to run it. I have tried to run a "runjava.bat" and get the .bat to run the "Runable.java" class but I keep getting a "Error: Could not find or load main class application.Runable.class". I was wondering what I am doing wrong or if there is a better way to go about running a java class from within a java program?
Here is my code(Simplify Slightly):
Main.java:
package application;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.stage.FileChooser;
public class Main {
final static String Program =
"package application;\n"
+ "public class Runable {\n"
+ "public static void main(String[] args) {\n"
+ "System.out.println(\"Hello\");\n"
+ "}\n"
+ "}\n";
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
while(true){
System.out.println("State a comand.");
String Command = s.nextLine();
if (Command.equalsIgnoreCase("Write") || Command.equalsIgnoreCase("Save")){
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = new File("src/application/Runable.class");
if(file != null){
SaveFile(Program, file);
}
}
else if (Command.equalsIgnoreCase("Run") || Command.equalsIgnoreCase("Play")){
ProcessBuilder builder = new ProcessBuilder(
"src/runjava.bat");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
else if (Command.equalsIgnoreCase("End") || Command.equalsIgnoreCase("Exit")){
Platform.exit();
}
else{
System.err.println("Command not recognized.");
System.err.println("Please try again.");
}
}
}
private static void SaveFile(String content, File file){
try {
FileWriter fileWriter = null;
fileWriter = new FileWriter(file);
fileWriter.write(content);
fileWriter.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
runjava.bat:
javac "src\application\Runable.java"
java application.Runable.class
and Runable.java if you didn't get it from the Main.java:
package application;
public class Runable {
public static void main(String[] args) {
System.out.println("Hello");
}
}
The java command expects a class name, not a filename. Unless your class is called "class" in the package "application.Runable" (which it isn't) you probably wanted to use:
java application.Runable
Because you can't execute a .java file like that. You must first compile it to get a .class file, and change the code that executes the class to point to Runable.class
The reason it is not running, is because the .java file is the code you type, and the .class file is the compiled version of the code that Java Virtual Machine executes.
Another solution to compile and run the program compared to executing the .bat file is to use the javax.tools API or another library based off of it. I have found InMemoryJavaCompiler library that makes it easy to compile and run the programs. This approach means that the program will run on the same JVM as your UI which may be helpful.
The following code shows how you might invoke the program using the library.
try{
Class<?> clazz = InMemoryJavaCompiler.compile("apllication.Runable", Program);
clazz.getMethod("main", String[].class).invoke(null, new String[0]);
}catch(Exception e){
e.printStackTrace();
}
In your Main.java's "Run" block, you should have
ProcessBuilder builder = new ProcessBuilder("runjava.bat");
In your runjava.bat, you should have (as immibis said)
javac -d . src/application/Runable.java
java application.Runable
** not Runable.class in the second line.
And runjava.bat should be placed in parallel with the parent folder of application\ but not the src\application folder. In other words, you should have something like classes\runjava.bat, classes\application\Main.class and classes\application\Runable.class. Hope it helps.
Here is my code:
import org.apache.poi.hslf.HSLFSlideShow;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.usermodel.SlideShow;
import java.io.*;
public class CreateNewPresentation
{
public static void main(args[])
{
try
{
SlideShow slideShow = new SlideShow();
Slide slide = slideShow.createSlide();
FileOutputStream out = new
FileOutputStream("slideshow.ppt");
slideShow.write(out);
System.out.println("File Created...");
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
The issue is that it does not recognise org.apache.poi package.
How can I make it work?
If you are using netbeans, refer this for setting classpath.
If you want to set classpath from command line refer this
I currently have this code to open an xlsx file using apache POI
File existingXlsx = new File("/app/app.xlsx");
System.out.println("File Exists: " + existingXlsx.exists());
Workbook workbook = WorkbookFactory.create(existingXlsx);
When I try to execute this, I get the following output
File Exists: true
java.lang.NullPointerException
at org.apache.poi.xssf.usermodel.XSSFWorkbook.onDocumentRead(XSSFWorkbook.java:270)
at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:159)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:186)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:91)
The file I am trying to open can be opened in Excel and show the data correctly, what can I do to get POI to read the XLSX file?
Here is the file that breaks;
https://mega.co.nz/#!FJMWjQKI!CzihQgMVpxOQDTXzSnb3UFYSKbx4yFTb03-LI3iLmkE
Edit
I have also tried, this results in the same error;
Workbook workbook = new XSSFWorkbook(new FileInputStream(existingXlsx));
Edit
I found the line it is throwing the exception on;
WorkbookDocument doc = WorkbookDocument.Factory.parse(getPackagePart().getInputStream());
this.workbook = doc.getWorkbook();
Map<String, XSSFSheet> shIdMap = new HashMap<String, XSSFSheet>();
for(POIXMLDocumentPart p : getRelations())
{
if(p instanceof SharedStringsTable) sharedStringSource = (SharedStringsTable)p;
else if(p instanceof StylesTable) stylesSource = (StylesTable)p;
else if(p instanceof ThemesTable) theme = (ThemesTable)p;
else if(p instanceof CalculationChain) calcChain = (CalculationChain)p;
else if(p instanceof MapInfo) mapInfo = (MapInfo)p;
else if (p instanceof XSSFSheet) {
shIdMap.put(p.getPackageRelationship().getId(), (XSSFSheet)p);
}
}
stylesSource.setTheme(theme); <== BREAKS HERE
Edit
After some research POI seems to be unable to find the styles.xml and the workbook.xml, I find this strange because a simple reader like TextWrangler which shows the structure of the archive shows me the styles xml.
How do I fix this? Is there a default styles.xml and workbook.xml which I can insert into the archive?
Now I've dowloaded the latest packages:
poi-src-3.9-20121203.zip (As source)
xmlbeans-2.6.0.zip
jsr173_1.0_api.jar
resolver.jar
xbean.jar
xbean_xpath.jar
xmlbeans-qname.jar
xmlpublic.jar
ooxml-schemas-1.1.jar
dom4j-1.6.1.jar
commons-codec-1.8.jar
commons-logging-1.1.3.jar
ant.jar (ant 1.7)
And your test2.xlsx were read without problems:
public static void main(String arg []){
try {
//File existingXlsx = new File("/app/app.xlsx");
File existingXlsx = new File("c:/Java/poi-3.9/test-data/__theproblem/test2.xlsx");
System.out.println("File Exists: " + existingXlsx.exists());
Workbook workbook = WorkbookFactory.create(existingXlsx);
} catch (Exception e) {
e.printStackTrace();
}
}
Are you sure you're using ooxml-schemas-1.1.jar as the POI documentation recommends?
EDIT
Hmm. It's work for me from jar too.
I have downloaded poi-bin-3.9-20121203.tar.gz from
http://poi.apache.org/download.html
Made a new project in Eclipse, extracted all the jars from the zip:
lib/commons-codec-1.5.jar
lib/commons-logging-1.1.jar
lib/dom4j-1.6.1.jar
lib/junit-3.8.1.jar
lib/log4j-1.2.13.jar
lib/poi-3.9-20121203.jar
lib/poi-examples-3.9-20121203.jar
lib/poi-excelant-3.9-20121203.jar
lib/poi-ooxml-3.9-20121203.jar
lib/poi-ooxml-schemas-3.9-20121203.jar
lib/poi-scratchpad-3.9-20121203.jar
lib/stax-api-1.0.1.jar
lib/xmlbeans-2.3.0.jar
Add the test xlsx:
test-data/test2.xlsx
The test Java:
src/XlsxReadTest1.java
Source:
import java.io.File;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class XlsxReadTest1 {
public static void main(String arg []){
try {
File existingXlsx = new File("c:/Java/__Work/apache_POI/poi-3.9-bin/test-data/test2.xlsx");
System.out.println("File Exists: " + existingXlsx.exists());
Workbook workbook = WorkbookFactory.create(existingXlsx);
System.out.println("A1: " + workbook.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Run. (Tried with jdk1.7.0_07, jdk1.6.0_31)
Result:
File Exists: true
A1: Testing Edit
"Testing Edit" is the content of the first cell on the first sheet of your file.
I think, You may try this, from scratch.
(Maybe you are using other jars for your project, whom interfere with this jars in the class loader? Class loader is a cunning guy...)
I guess you just used the wrong poi package.
Try to download the following or you check the newest version from the page.
The following I tested in my Eclipse development:
http://www.apache.org/dyn/closer.cgi/poi/release/bin/poi-bin-3.9-20121203.zip
extract it, and include all the jars into your eclipse lib
I combine user1234's answer and my own approach, both are working on your test2.xlsx
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.XmlException;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// File existingXlsx = new File("app.xlsx");
File file = new File("test2.xlsx");
FileInputStream fs;
try {
fs = new FileInputStream(file);
OPCPackage xlsx = OPCPackage.open(fs);
XSSFExcelExtractor xe = new XSSFExcelExtractor(xlsx);
System.out.println(xe.getText());
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (XmlException e) {
e.printStackTrace();
} catch (OpenXML4JException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/// -------------- Another approach
File existingXlsx = new File("test2.xlsx");
System.out.println("File Exists: " + existingXlsx.exists());
try {
Workbook workbook = new XSSFWorkbook(new FileInputStream(
existingXlsx));
Sheet worksheet = workbook.getSheet("Filter criteria");
Row row1 = worksheet.getRow(0);
Cell cellA1 = row1.getCell((short) 0);
String a1Val = cellA1.getStringCellValue();
System.out.println("A1: " + a1Val);
} catch (IOException e) {
e.printStackTrace();
}
}
}
finally I got the result:
If you want to read .xlsx, could you please try this code (uses apache poi 3.9) :
File file = new File("/app/app.xlsx");
FileInputStream fs = new FileInputStream(file);
OPCPackage xlsx = OPCPackage.open(fs);
XSSFExcelExtractor xe = new XSSFExcelExtractor(xlsx);
System.out.println(xe.getText());
The above code should display the content of the file app.xlsx.
I'm programming using the SWT Widget Library for Java in eclipse, and I'm designing a runnable Java application. I've got the application down, I just don't know how to load external .swf files from a folder on "ALL" computers. I can load Images from any computer, because I use the getResourceAsStream line of code. But the "import com.docuverse.swt.flash.FlashPlayer" "loadMovie(arg, arg)" only takes a String.
So I did ClassName.class.getResource("blah.swf").getPath(); which gives you a string, I set it up, and running it on eclipse it can perfectly find the file in the package. When I export it, the runnable Jar I made cannot find the "blah.swf" inside of the .jar file.
So there is my problem, how do I load my .swf files from within the .jar or from an external folder so clients can download along side the .jar executable application, so it can point to those swf files.
Thankyou.
Here is the way I talked about in comments (creating temp file and save flash animation from jar to it)
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import com.docuverse.swt.flash.FlashPlayer;
public class SWTFlashPlayer {
private FlashPlayer player = null;
private final String FLASH_FILE_PATH = "/EdnCateDance.swf";
private final String TMP_FILE_PREFFIX = "tmp_";
private final String TMP_FILE_SUFFIX = ".swf";
private File swfFile = null;
public SWTFlashPlayer() {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
try {
swfFile = copyFileFromJar(FLASH_FILE_PATH, TMP_FILE_PREFFIX, TMP_FILE_SUFFIX);
} catch (IOException e) {
e.printStackTrace();
return;
}
player = new FlashPlayer(shell, SWT.NONE);
player.loadMovie(0, swfFile.getAbsolutePath());
player.setSize(150, 150);
player.activate();
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
/**
* Copy file packed inside current jar to temp file
* #param jarPath String - path inside jar
* #param filePreffix String - temp file preffix
* #param fileSuffix - temp file suffix
* #throws IOException - temp file cannot be created or writing somehow fails
*/
private File copyFileFromJar(String jarPath, String filePreffix, String fileSuffix) throws IOException {
File toFile = File.createTempFile(filePreffix, fileSuffix);
// delete file after application finishes
toFile.deleteOnExit();
if(!toFile.canWrite()) throw new IOException("File (" + toFile.getPath() + ") not exists or is not writable!");
FileOutputStream fos = new FileOutputStream(toFile);
InputStream is = this.getClass().getResourceAsStream(jarPath);
if(is == null) throw new IOException("File on jar path could not be located or loaded!");
int read = 0;
byte bytes[] = new byte[1024];
while ((read = is.read(bytes)) != -1) {
fos.write(bytes, 0, read);
}
fos.flush();
fos.close();
return toFile;
}
public static void main(String[] args) {
new SWTFlashPlayer();
}
}
I used the EdnCateDance.swf flash file which is one of the examples in SWT Flash library.