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);
}
}
}
}
Related
I am working on a LWJGL project, and I cannot get the native libraries to work. I can run it in the IDE just fine, but when I export it, it crashes. But here is the problem, I made a bit of code to extract the native files from the Jar, and into a temporary folder, once that is done, it attempts to load the native, but it gives this error:
java.lang.UnsatisfiedLinkError: no jinput-dx8 in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)
at java.lang.Runtime.loadLibrary0(Runtime.java:870)
at java.lang.System.loadLibrary(System.java:1122)
at com.test.opengl.engineTester.NativeSupport.loadDLL(NativeSupport.java:46)
at com.test.opengl.engineTester.NativeSupport.extract(NativeSupport.java:23)
at com.test.opengl.engineTester.MainGameLoop.<clinit>(MainGameLoop.java:21)
NativeSupport.class:
import java.io.*;
import java.util.Date;
public class NativeSupport {
private static File tempLocation;
public static void extract() {
tempLocation = new File(System.getProperty("java.io.tmpdir") + "/OpenGL_Test_" + new Date().getTime() + "/");
tempLocation.deleteOnExit();
tempLocation.mkdirs();
System.out.println(System.getProperty("java.library.path"));
String path = tempLocation.getAbsolutePath()+"\\;";
System.setProperty("java.library.path", path);
System.out.println(path);
loadDLL("jinput-dx8.dll");
loadDLL("jinput-dx8_64.dll");
loadDLL("jinput-raw.dll");
loadDLL("jinput-raw_64.dll");
loadDLL("lwjgl.dll");
loadDLL("lwjgl64.dll");
loadDLL("OpenAL32.dll");
loadDLL("OpenAL64.dll");
}
private static void loadDLL(String name) {
try {
System.out.println(name);
BufferedReader in = new BufferedReader(new InputStreamReader(Class.class.getResourceAsStream("/"+name)));
File fileOut = new File(tempLocation, name);
System.out.println(fileOut.getAbsolutePath());
FileWriter out = new FileWriter(fileOut);
char[] buffer = new char[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
System.loadLibrary(fileOut.getName().substring(0, fileOut.getName().length()-4)); // Here is where the crash happens
} catch (Exception e) {
e.printStackTrace();
}
}
public static void clean() {
}
}
The extract method is called in a static call from MainGameLoop.class. I have tried calling it in the main function, and it did the same thing. I also made sure that the files existed before they were loaded.
I would like to avoid the Jar Splice program.
If I was unclear about anything, I will be back with this question in about a day to tidy up my question (I am up at 03:00 trying to solve this problem)
Thanks for your help, I really appreciate it.
Some time ago I have developed sample code that can help you here. Take a look here:
https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo031
You can find there few components:
library extractor (it takes care for getting native code from jar file)
HelloWorld class that uses arbitrary located native file
Main class that takes care of everything
In your case, I'd use System.load instead of System.loadLibrary. You have the file anyway on your file system.
Have fun with JNI.
For more samples related to JNI, take a look here: http://jnicookbook.owsiak.org
I have over 100 images I need to associate to newly created ImageIcon objects. How can I import them faster than manually typing this for each image?
ImageIcon imagefile = new ImageIcon("imagefile")
I'm coding in Eclipse.
well you could write some code to write code for you (if thats what you need to do. )
Then once the code has been output you can copy/paste it into the class in your application.
For example something like this would save you a lot of typing:
import java.io.*;
public class CodeWritingDemo {
public static void main(String[] args) throws Exception {
String rootFolder = "src/res/"; // or args[0]
File folder = new File(rootFolder);
for (File file : folder.listFiles()) {
if (file.getName().toLowerCase().endsWith("png") || file.getName().toLowerCase().endsWith("jpg")) {
printFilename(file, "src/".length());
}
}
}
public static void printFilename(File file, int stripIndex) {
String variableName = file.getName().replaceAll("[.]", "_");
String template = "ImageIcon " + variableName + " = new ImageIcon(\"" + file.getPath().substring(stripIndex) + "\")";
System.out.println(template);
}
}
If you desire you could modify the System.out.println in the printFilename method to automatically write code to do something such as add these items to a list or a hashmap.
Im trying to read 100 text files from a folder and save them to a matrix, and it works perfectly for the first 99 text files. This could be a trivial mistake, but I can not find it. Thank you in advance!
package mba_prob;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ConverTo {
public static void main(String[] args) throws NumberFormatException, IOException{
String target_dir = "/directory";
File dir = new File(target_dir);
File[] files = dir.listFiles();
for (File f : files) {
if(f.isFile()) {
double [][]thematrix = readMatrix(f);
}
}
}
}
Is it possible that the last file is in use?
Try using java.io.File.exists()
for (File f : files) {
if(f.exists()) {
double [][]thematrix = readMatrix(f);
}
}
Java File.exists() versus File.isFile()
I have a homework to do and I don't know how to get started. I have to read from an external text file the paths of some random folders. I must make the paths for this folders available even I change the computer.
Then I have to output in the console the number of mp3 files found in every each folder.
My big problem is that I don't know how to make those paths work for every computer on which I run the program and also I don't know how the filter the content.
LATER EDIT: I've managed to write some code. I can search now for the mp3, but... can someone help me with this: how can i add a new path to the txt file from keyboard and also how can i remove an entire line from it?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String ext = ".mp3";
BufferedReader br = new BufferedReader(new FileReader("Monitor.txt"));
for (String line; (line = br.readLine()) != null;) {
findFiles(line, ext);
}
br.close();
}
private static void findFiles(String dir, String ext) {
File file = new File(dir);
if (!file.exists())
System.out.println(dir + " No such folder folder");
File[] listFiles = file.listFiles(new FiltruTxt(ext));
if (listFiles.length == 0) {
System.out.println(dir + " no file with extension " + ext);
} else {
for (File f : listFiles)
System.out.println("Fisier: " + f.getAbsolutePath());
}
}
}
import java.io.File;
import java.io.FilenameFilter;
public class FiltruTxt implements FilenameFilter{
private String ext;
public FiltruTxt(String ext){
this.ext = ext.toLowerCase();
}
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(ext);
}
}
I think that with "available even I change the computer" mean that you need to read the path from the file and not hard code it on your program so if you run in other computer you only need to change the text file and not the program.
But as #André Stannek had said in his comment, you must add to your question what have you tried and what is the exact programming problem you are facing.
When you face a problem, try to divide it in individual and more small problems. For example:
How to read a line from the console?
How to write a new line to a file?
Then try to search for a solution (if you can't think in one). For example in stack overflow, google and of course in the official documentation.
The official documentation:
http://docs.oracle.com/javase/tutorial/essential/io/index.html
Some questions in stackoverflow:
Read multiple lines from console and store it in array list in Java?
Read string line from console
How do I add / delete a line from a text file?
How to add a new line of text to an existing file in Java?
Or this links from Internet:
http://www.msccomputerscience.com/2013/01/write-java-program-to-get-input-from.html
This is the portal of the Java tutorials that you will found very useful when you are learning: http://docs.oracle.com/javase/tutorial/index.html
I want to read all the images in a folder using Java.
When: I press a button in the Java application,
It should:
ask for the directory's path in a popup,
then load all the images from this directory,
then display their names, dimension types and size.
How to proceed?
I have the code for read the image and also for all image in the folder but how the things i told above can be done?
Any suggestion or help is welcome! Please provide reference links!
Untested because not on a machine with a JDK installed, so bear with me, that's all typed-in "as-is", but should get you started (expect a rush of downvotes...)
Loading all the Images from a Folder
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Test {
// File representing the folder that you select using a FileChooser
static final File dir = new File("PATH_TO_YOUR_DIRECTORY");
// array of supported extensions (use a List if you prefer)
static final String[] EXTENSIONS = new String[]{
"gif", "png", "bmp" // and other formats you need
};
// filter to identify images based on their extensions
static final FilenameFilter IMAGE_FILTER = new FilenameFilter() {
#Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
public static void main(String[] args) {
if (dir.isDirectory()) { // make sure it's a directory
for (final File f : dir.listFiles(IMAGE_FILTER)) {
BufferedImage img = null;
try {
img = ImageIO.read(f);
// you probably want something more involved here
// to display in your UI
System.out.println("image: " + f.getName());
System.out.println(" width : " + img.getWidth());
System.out.println(" height: " + img.getHeight());
System.out.println(" size : " + f.length());
} catch (final IOException e) {
// handle errors here
}
}
}
}
}
APIs Used
This is relatively simple to do and uses only standard JDK-packaged classes:
File
FilenameFilter
BufferedImage
ImageIO
These sessions of the Java Tutorial might help you as well:
Reading/Loading an Image
How to Use Icons
How to Use File Choosers
Possible Enhancements
Use Apache Commons FilenameUtils to extract files' extensions
Detect files based on actual mime-types or content, not based on extensions
I leave UI code up to you. As I'm unaware if this is homework or not, I don't want to provide a full solution. But to continue:
Look at a FileChooser to select the folder.
I assume you already know how to make frames/windows/dialogs.
Read the Java Tutorial How to Use Icons sections, which teaches you how to display and label them.
I left out some issues to be dealt with:
Exception handling
Folders with evil endigs (say you have a folder "TryMeIAmEvil.png")
By combining all of the above, it's pretty easy to do.
javaxt.io.Directory directory = new javaxt.io.Directory("C:\Users\Public\Pictures\Sample Pictures");
directory.getFiles();
javaxt.io.File[] files;
java.io.FileFilter filter = file -> !file.isHidden() && (file.isDirectory() || (file.getName().endsWith(".jpg")));
files = directory.getFiles(filter, true);
System.out.println(Arrays.toString(files));
step 1=first of all make a folder out of webapps
step2= write code to uploading a image in ur folder
step3=write a code to display a image in ur respective jsp,html,jframe what u want
this is folder=(images)
reading image for folder'
Image image = null;
try {
File sourceimage = new File("D:\\images\\slide4.jpg");
image = ImageIO.read(sourceimage);
} catch (IOException e) {
e.printStackTrace();
}
}