Thursday, July 11, 2013

Copy Files

FileCopy is a simple program that can help you to copy files in your local computer from a source directory to a destination directory. There are two choices for you. You can copy files by extension. If you want to copy all files, write *. for the file extension.

copy files by extensions


Another option is that you can copy files by date modified. If you want copy files that their date modified is equal to your date input, write 0 for comparison parameter. By writing -1 for the comparison parameter, files with dates modified greater than your date input are copied. In contrast, writing 1 for the comparison parameter is to copy files that have dates modifies less than the date input.

copy files by date modified

FileCopy source code:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Date;
import org.joda.time.LocalDate;

public class FileCopy{
public static void main(String[] args){

                System.out.println("........EASY FILES COPY......");
startProgram();

}

public static void copyFileByExt(){
try{
//create text reader to read text from keyboard
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//allow source directory input
System.out.println("Enter source directory:");
String from_dir=br.readLine();
//create file object to encapsulate the source directory
File fromDir=new File(from_dir);
//check source directory existence
if(!fromDir.exists())
{
System.out.println("Source directory deos not exist.");
System.exit(-1);
}
//allow destination directory input
System.out.println("Enter destination directory:");
String to_dir=br.readLine();
//create file object to encapsulate the source directory
File toDir=new File(to_dir);
if(!toDir.exists())
toDir.mkdir();
//allow file extension input
System.out.println("Enter file extension:");
String ext=br.readLine();
if(ext!=""){
String[] files;
if(ext.equals("*."))
files=fromDir.list(); //select all files
else
files=fromDir.list(new ExtFilter(ext)); //select only files of specified extension
System.out.println("Please wait...");
for(String s:files){
File myfile=new File(fromDir+"/"+s);
if(myfile.isFile()){
System.out.println("Copying "+fromDir+"/"+s+" to "+to_dir);
copy(fromDir+"/"+s,toDir+"/"+s);
}
}
System.out.println("Compy completed.");

}
}catch(IOException ie){ie.printStackTrace();}
}

public static void copyFileByModifyDate(){
try{
//create text reader to read text from keyboard
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//allow source directory input
System.out.println("Enter source directory:");
String from_dir=br.readLine();
//create file object to encapsulate the source directory
File fromDir=new File(from_dir);
//checking source directory existence
if(!fromDir.exists())
{
System.out.println("Source directory deos not exist.");
System.exit(-1);
}
//allow destination directory input
System.out.println("Enter destination directory:");
String to_dir=br.readLine();
//create file object to encapsulate the destination directory
File toDir=new File(to_dir);
if(!toDir.exists())
toDir.mkdir();
//allow the date modified input used for comparison
System.out.println("Enter the date modified(e.g. 2013-02-16):");
String modify_date=br.readLine();
//allow comparison value input
//0 means copy all files that their dates modified  are equal to the input date
//1 means copy all files that their dates modified  are less than the input date
//-1 means copy all files that their dates modified  are greater than the input date

System.out.println("Enter comparison value (0, 1, or -1):");
int com=Integer.parseInt(br.readLine());
String[] files=fromDir.list();
System.out.println("Please wait...");
for(String s:files){
File myFile=new File(from_dir+"/"+s);
if(myFile.isFile()){
LocalDate localdate=LocalDate.parse(modify_date);
LocalDate modate=LocalDate.fromDateFields(new Date(myFile.lastModified()));
int x=localdate.compareTo(modate);
if(x==com){
System.out.println("Copying "+from_dir+"/"+s+" to "+to_dir);
copy(from_dir+"/"+s,to_dir+"/"+s);
}
}
}
System.out.println("Copy completed");

}catch(IOException ie){}

}
public static void copy(String srcfile, String descfile){
try{
//create stream reader
FileInputStream fis=new FileInputStream(srcfile);
//create stream writer
FileOutputStream fos=new FileOutputStream(descfile);
int data;
//start copying
while((data=fis.read())!=-1){
fos.write(data);

}
fos.flush();
fos.close();
fis.close();
}catch(IOException ie){}

}

public static void startProgram(){
int ch;
char con='y';
Scanner sc=new Scanner(System.in); //create scanner object to receive choice input

while(con=='y'){
showCopyOptions(); //show menu
System.out.println("Enter your choice:");
ch=sc.nextInt();
switch(ch){
case 1:copyFileByExt();break;
case 2:copyFileByModifyDate();break;
case 3:System.exit(0);break;
default:System.out.println("Invalid choice");
}

try{
//prompt for continuing the program
InputStreamReader isr=new InputStreamReader(System.in);
System.out.println("Press y to continue:");
con=(char)isr.read();
}catch(IOException ie){}


}
}
public static void showCopyOptions(){
System.out.println("1. Copy files by extension");
                System.out.println("2. Copy files by date modified");
System.out.println("3. Exit program");
}

}

class ExtFilter implements FilenameFilter{
String ext="";
public ExtFilter(String ext){
this.ext="."+ext;
}
public boolean accept(File f, String name){
if(name.endsWith(ext)) return true;
else return false;

}
}


Wednesday, July 10, 2013

Pdf reader

PdfReader is a simple pdf reader program. The main api used in this program is PDFRenderer . At the right side bar in the reference list, you will find a link to get more information about the PDFRenderer api.
With PdfReader you can select a PDF file to be viewed, move one page forward and backward, zoom the page in and out, go to a specific page, save the page in image format, and print the PDF document to a default printer in your computer system.


pdf reader in java

PdfReader source code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;


class Starter extends JFrame implements ActionListener{
Rectangle rect;
PDFPage page;
Image img;
int adjx=0;
int adjy=0;
JLabel lblimg;
PDFFile pdf;
File f;
int pageNum=1;
int numPages;
JTextField txtPNum;
JButton btnext;
JButton btpre;
JButton btin;
JButton btout;
JButton btcapture;
JButton btprint;
JPanel panel;


public Starter(String title){

Container cont=getContentPane(); //get container of the JFrame
cont.setLayout(new BorderLayout()); //apply border layout to the container
//Show File menu
JMenuBar mainmenu=new JMenuBar();
JMenu menu=new JMenu("File");
JMenuItem mopen=new JMenuItem("Open...");
mopen.setMnemonic(KeyEvent.VK_O);
mopen.addActionListener(this);
JMenuItem mexit=new JMenuItem("Exit");
mexit.setMnemonic(KeyEvent.VK_X);
mexit.addActionListener(this);
menu.add(mopen);
menu.add(mexit);
mainmenu.add(menu);
    setJMenuBar(mainmenu);
    //show buttons, labels, and a text box
panel=new JPanel();
JButton btnext=new JButton(">");
JButton btpre=new JButton("<");
JButton btin=new JButton("+");
JButton btout=new JButton("-");
txtPNum=new JTextField();
txtPNum.addKeyListener(new KeyA());
JLabel lblPNum=new JLabel("Page:");
lblPNum.setHorizontalAlignment(JLabel.CENTER);
btcapture=new JButton("Capture");
btprint=new JButton("Print");
btnext.addActionListener(this);
btpre.addActionListener(this);
btin.addActionListener(this);
btout.addActionListener(this);
btcapture.addActionListener(this);
btprint.addActionListener(this);
panel.setLayout(new GridLayout(1,6));
panel.setBackground(Color.BLACK);
panel.add(btnext);
panel.add(btpre);
panel.add(btin);
panel.add(btout);
panel.add(lblPNum);
panel.add(txtPNum);
panel.add(btcapture);
panel.add(btprint);
applyComponentStyles();
cont.add(panel,BorderLayout.NORTH);
lblimg=new JLabel();
lblimg.setHorizontalAlignment(JLabel.CENTER);
JScrollPane jscroll=new JScrollPane(lblimg);
cont.add(jscroll,BorderLayout.CENTER);
setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH);
setTitle(title); //set the title of the JFrame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//closable JFrame
setVisible(true);
setIconImage(getToolkit().getImage("pdfviewicon.png"));
panel.setVisible(false);
}

public void getFile(String filename){
//read pdf file and place its data in PDFFile object for later use
try{
f=new File(filename); //create file object
RandomAccessFile raf=new RandomAccessFile(f,"r"); //open the file for reading
FileChannel pc=raf.getChannel(); //get the file channel
ByteBuffer buffer=pc.map(FileChannel.MapMode.READ_ONLY, 0, pc.size()); //store file data in the memory
pdf=new PDFFile(buffer);//place the file data in memory in PDFFile object
numPages=pdf.getNumPages(); //get the number of pages of the pdf document
raf.close();//close reader
moveFist(); //show the first page


}catch(IOException e){System.out.println("Error in open the file");System.exit(-1);}

}

//apply background, text colors, and font to components
public void applyComponentStyles(){
Component[] coms=panel.getComponents();
for(Component c:coms){
c.setBackground(Color.BLACK);
c.setForeground(Color.WHITE);
c.setFont(new Font("Arial",Font.BOLD,15));

}
}


//do an action when a button or menu item is selected
public void actionPerformed(ActionEvent e){


if(e.getActionCommand().equals("+"))
doZoomin();
else if(e.getActionCommand().equals("-"))
doZoomout();
else if(e.getActionCommand().equals(">"))
moveNext();
else if(e.getActionCommand().equals("<"))
movePrevious();
else if(e.getActionCommand().equals("Capture"))
capturePage(img);
else if(e.getActionCommand().equals("Print"))
print();

else if(e.getActionCommand().equals("Open..."))
selectPDF();
else if(e.getActionCommand().equals("Exit"))
System.exit(0);

}

public void print(){
Desktop dt=Desktop.getDesktop();
try{
dt.print(f);
}catch(IOException ie){}
}
//display the pdf page as an image on the JLabel lblimg
public void showImage(){
int w=rect.width+adjx;
        int h=rect.height+adjy;
        img = page.getImage(
                w,h, //width & height
                rect, // clip rect
                null, // null for the ImageObserver
                true, // fill background with white
                true  // block until drawing is done
                );
        lblimg.setIcon(new ImageIcon(img));
        txtPNum.setText(page.getPageNumber()+"");
     
}
//increase the image page size
public void doZoomin(){
adjx+=10;
adjy+=10;
        showImage();
        repaint();
}
//decrease the image page size
public void doZoomout(){
adjx-=10;
adjy-=10;
        showImage();
        repaint();
}
//move to first page
public void moveFist(){
pageNum=1;
displayPage(pageNum);

}
//move to next page
public void moveNext(){
if(pageNum<numPages){
pageNum+=1;
displayPage(pageNum);
}

}
//move to previous page
public void movePrevious(){
if(pageNum>0){
pageNum-=1;
displayPage(pageNum);
}
}
//goto a page
public void gotoPage(int num){
if(num>=0 && num<=numPages){
displayPage(num);
pageNum=num; //update pageNum to the current page
}

}
//get the page and show it
public void displayPage(int n){
page=pdf.getPage(n); //get the current page
//get the width and height of the page
rect = new Rectangle(0,0,(int)page.getBBox().getWidth(),(int)page.getBBox().getHeight());
showImage(); //show the page
 
}
//The createBufferedImageFromImage method is able to generate a buffered image from an input image
public void capturePage(Image image)
  {
int width=image.getWidth(null);
int height= image.getHeight(null);
  BufferedImage dest = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = dest.createGraphics();
    g2.drawImage(image, 0, 0,width, height, null);
    g2.dispose();
    try{
   
    ImageIO.write(dest, "png", new File("pdfpage"+pageNum+".png"));
   
    }catch(IOException ie){}
   
  }

class KeyA extends KeyAdapter{
public void keyReleased(KeyEvent ke){
char c = ke.getKeyChar();
int intkey=(int)c;
if(!(intkey>=48 && intkey<=57 || intkey==8))
  {
ke.consume(); //hide the unwanted key

  }
else
if(!txtPNum.getText().equals("")){
gotoPage(Integer.parseInt(txtPNum.getText()));
}
}
}

public void selectPDF(){

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF","pdf");
chooser.setFileFilter(filter);
chooser.setMultiSelectionEnabled(false);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file=chooser.getSelectedFile();
getFile(file.toString());
panel.setVisible(true);
}

     
}
}


public class PdfReader {
public static void main(String[] args){
new Starter("PDF Reader");
}


}

Friday, July 5, 2013

HTML To PDF Converter

HTMLToPDFConverter is able to convert multiple html files to PDF files.  It is easy to use. The program provides you two options. First, you can select html files in your local computer to be converted to PDF files. A file open dialog is shown. It allows you to select html files from your local computer. You will wait for a while to complete the conversion task.

html to pdf converter local files selection


Another option allows you to convert html files on the web to PDF files. You will need to type or paste the address of the html page in to the Address box and click Add to add this address to the conversion list. You can add many html pages as you want. After adding all addresses that you want  to the list, click OK and wait a moment until the conversion task finishes.

html to pdf converter web pages selection


Technically, to convert an html file to a PDF file, there are few steps that have to be taken. These steps are:
-After the html file is read, it is cleaned. The Jsoup library is used to clean the html file.
-The cleaned html file is converted to xhtml file by using the Jtidy library.
-The final step is to convert the xhtml file to a PDF file by using XMLWorker library.

HTMLToPDFConverter source code:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.jsoup.Jsoup;
import org.w3c.tidy.Tidy;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class HTMLToPDFConverter{
public static void main(String[] args){

System.out.println("........HTML to PDF Converter......");
int ch;
Scanner sc=new Scanner(System.in);
showOptions();
System.out.println("Enter your choice:");
ch=sc.nextInt();
switch(ch){
case 1: selectLocal();break;
case 2: selectWeb();break;
case 3: System.exit(0);
default: System.out.println("Invalid choice");
}



}


public static void selectLocal(){
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("HTML", "html", "htm");
chooser.setFileFilter(filter);
chooser.setMultiSelectionEnabled(true);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File[] Files=chooser.getSelectedFiles();
System.out.println("Please wait...");
        for( int i=0;i<Files.length;i++){    
        String address="file:///"+Files[i].toString();
        loadHTML(address);
        convertHTMLToPDF();
        }
System.out.println("Conversion complete");
        }
}
public static void selectWeb(){
new LinksAdd("Add links");

}

//display a window to add links to the list for conversion

static class LinksAdd extends JFrame implements ActionListener{
DefaultListModel listmodel;
JTextField textlink;
JLabel lblwait;

LinksAdd(String title){
Container cont=getContentPane();
cont.setLayout(new BorderLayout());
setTitle(title);
setPreferredSize(new Dimension(600,300));
JLabel lbl=new JLabel("Address:");
textlink=new JTextField(30);
JButton btadd=new JButton("Add");
btadd.addActionListener(this);
JPanel panelnorth=new JPanel();
panelnorth.add(lbl);
panelnorth.add(textlink);
panelnorth.add(btadd);
listmodel=new DefaultListModel();
JList linkslist=new JList(listmodel);
linkslist.setVisibleRowCount(10);
linkslist.setFixedCellWidth(200);
JScrollPane pane=new JScrollPane(linkslist);
JButton btok=new JButton("OK");
lblwait=new JLabel();
JPanel panelsouth=new JPanel();
panelsouth.add(btok);
panelsouth.add(lblwait);
btok.addActionListener(this);
cont.add(panelnorth, BorderLayout.NORTH);
cont.add(pane, BorderLayout.CENTER);
cont.add(panelsouth, BorderLayout.SOUTH);

pack();
setVisible(true);
}

public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Add")){
if(!textlink.getText().equals("")){
listmodel.addElement(textlink.getText());
textlink.setText("");
}

}
else if(e.getActionCommand().equals("OK")){
Thread t=new Thread(){
public void run(){
lblwait.setText("Please wait...");

for(int i=0;i<listmodel.size();i++){
loadHTML(listmodel.getElementAt(i).toString());
convertHTMLToPDF();
}
dispose();
}
};
t.start();


}
}
}

//read, and convert the original html to xhtml file
//by using parse method of Tidy class
public static void loadHTML(String src){
Tidy tidy=new Tidy();
tidy.setMakeClean(true);
tidy.setXHTML(true);
try{

URL url=new URL(src);
File cleanedHTMLFile=cleanHTML(url.openStream());
tidy.parse(new FileInputStream(cleanedHTMLFile),new FileOutputStream("d:/tempfile.xhtml"));
}catch(Exception fnfe){
System.out.println("The file can't be read.");
System.exit(-1);
}
}
//convert the xhtml file to PDF file by using
//the parseXHtml method of the XMLWorkerHelper class
public static void convertHTMLToPDF(){
try{

Document doc=new Document();
PdfWriter pw=PdfWriter.getInstance(doc, new FileOutputStream(System.currentTimeMillis()+".pdf"));
doc.open();
XMLWorkerHelper.getInstance().parseXHtml(pw, doc, new FileInputStream("d:/tempfile.xhtml"));
doc.close();

}catch(Exception e){
System.out.println("Conversion can't be completed.");
System.exit(-1);}
}


public static File cleanHTML(InputStream srcstream){
String htmlfile="d:/cleanedhtml.html";

try{
org.jsoup.nodes.Document doc=Jsoup.parse(srcstream, "UTF-8", "");
Whitelist wlist=Whitelist.relaxed();
wlist.addAttributes(":all","style","href","ftp","http","https","class");
String cleanedBody=Jsoup.clean(doc.toString(),wlist);
Elements ls=doc.select("body");
ls.remove();
cleanedBody="<body>"+cleanedBody+"</body>";
String cleanedHTML=doc.toString().replaceFirst("</html>",cleanedBody+"</html>");
DataOutputStream dos=new DataOutputStream(new FileOutputStream(htmlfile));
dos.writeBytes(cleanedHTML);
dos.flush();
dos.close();

}catch(IOException ie){System.out.println("Unable to process the file");}
return new File(htmlfile);
}

public static void showOptions(){
System.out.println("1. html files from local computer");
System.out.println("2. html files from the web");

}


}
PDF To Word Converter, convert PDF To Word

Thursday, July 4, 2013

Extract links from html

The LinksExtractor is a simple program that can help you extract all links from an html web page. It is easy to use. When the input box displays, type or paste the address of any html web page to the box. Then click OK to begin links extracting process. The result links are stored in a text file called Links.txt in your current working folder.
The Apache Tika is the most important library used in th program. For more information about Apache Tika, you may need to visit its website. The website link can be found in the references list at the right side bar of this page.

extract links from html web page

links result

LinksExtractor source code:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import org.apache.tika.exception.TikaException;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.Link;
import org.apache.tika.sax.LinkContentHandler;
import org.xml.sax.SAXException;

public class LinksExtractor{

public static void main(String[] args){


try {
String address=JOptionPane.showInputDialog("Web page address:");
if(address!=null)
extractLinks(address,System.getProperty("user.dir")+"/links.txt");

} catch (Exception e) {

e.printStackTrace();
}


}

public static void extractLinks(String src, String desc) throws IOException, SAXException, TikaException{
BufferedWriter bw=null;

try{
//create stream read to read data from the url
InputStream f=TikaInputStream.get(new URL(src).openStream());
//create buffered writer to write extracted links to the file
bw=new BufferedWriter(new FileWriter(desc));
//create metadata to store the metadata of the web page
Metadata meta=new Metadata();
//create linkcontent hander to store the extracted links
LinkContentHandler linkhandler=new LinkContentHandler();
//create a parser to parse the web page file
AutoDetectParser parser=new AutoDetectParser();
//now parse the web page
parser.parse(f, linkhandler, meta);
//get links from the handler and write them to the file
List<Link> links=linkhandler.getLinks();
Iterator<Link> i=links.iterator();
while(i.hasNext()){
bw.write(i.next().toString());
bw.newLine();
}
}
//close the buffered writer
finally{
bw.flush();
bw.close();
}



}


}

Wednesday, July 3, 2013

File

Java provides File class that can be used to manage files and directories. Its constructor is File(String filepath). The useful methods of the File class are shown below:

-canRead() method tests whether the file can be read.
-canWrite() method tests whether the file can be modified.
-exists() method tests whether the file or directory exists.
-isFile() method tests whether the file denoted by the pathname is a normal file.
-isDirectory() method tests whether the file denoted by the pathname is a directory.
-delete() method deletes the file or directory. It returns true if deletion is successful. To delete a directory, it must be empty.
-createNewFile() method create a new file.
-length() method returns the length of the file in byte.
-mkdir() method creates a new directory.
-mkdirs() method creates a directory and its parent directories.
-list() method returns an array of string filenames and directory names.
-list(FilenameFilter filter) methods returns an array of string filenames that matches the filter.
-renameTo(File obj) method renames the file to another one specified as the File obj argument.

Example: show file and directory names in drive d:

import java.io.File;
public class FilesShow{

public static void main(String[] args){

showFiles("d:/");

}

public static void showFiles(String dir){

File f=new File(dir); //create file object to connect to the directory
if(!f.exists()){
System.out.println("Source directory does not exist.");
System.exit(-1);
}
else if(!f.isDirectory()){
System.out.println("It is not a directory.");
System.exit(-1);
}

String[] filenames=f.list(); //list file and directory names
for(String name:filenames){

System.out.println(name);

}


}



}

Tuesday, July 2, 2013

Move Files

With FileMover program, you can easily move your files from a source directory to another destination directory on your computer. You can choose to move all files or move only files that have a specific extension.
The program allows you to input source directory, file extension, destination directory, and override confirmation. If you want to move all files, input *. for the file extension. You can choose to override the existing files or not to override the existing files by inputting yes or no for the override confirmation.

move files in java

FileMover source code:

import java.io.File;
import java.io.IOException;
import java.io.FilenameFilter;


public class  FileMover{

public static void main(String args[]) throws IOException{

try{

moveFiles(args[0],args[1],args[2],args[3]);

}catch(ArrayIndexOutOfBoundsException aiobe){System.out.println("Invalid input parameters");}

}

public static void moveFiles(String fromDir,String ext,String toDir, String override){
//create file object to encapsulate the source directory
File from_dir=new File(fromDir);
//make the sure the source directory exists
if(!from_dir.exists()){
System.out.println("Source directory does not exist.");
System.exit(-1);
}

//create file object to encapsulate the destination directory
File to_dir=new File(toDir);
//check the existence of the destination directory
//if does not exist, create it
if(!to_dir.exists()){
boolean suc=to_dir.mkdirs();
if(!suc) {
System.out.println("Can't create the directory.");
System.exit(-1);
}
}
//make sure the destination directory is writable
else if(!to_dir.canWrite()){
System.out.println("Destination folder is not writable. Please input another folder.");
System.exit(-1);
}
String[] files;
if(!ext.equals("")){
if(!ext.equals("*.")) //select files with the specified extension
files=from_dir.list(new Filter(ext));
else //select all files
files=from_dir.list();

//Move files from input source directory to destination directory
for(String f:files){
File source=new File(from_dir+"/"+f);
if(source.isFile()){
File dest=new File(to_dir+"/"+f);
if(dest.exists() && override.equals("yes"))
dest.delete();
source.renameTo(dest);
}
}
}


}
}

class Filter implements FilenameFilter{
String ext="";
public Filter(String ext){
this.ext="."+ext;
}
public boolean accept(File f, String name){
if(name.endsWith(ext)) return true;
else return false;

}
}

In the code below, firstly we need to check whether the source directory exists or not. Moving files can not continue if the source directory does not exist. We also check the existence of the destination directory. If it does not exist, it will be created. After that the files in the source directory are listed. These can be all files int he directory or files that have a specified extension. The rename method of the File class is used to move files from the source to destination directory. If the override confirmation is yes, the existing files in the destination directories are deleted before moving the files to that directory.

Monday, July 1, 2013

Extract images from Word

WordImageExtractor is able to extract all images in a microsoft word 2007+ file. The Java library that is used to extract the images from the microsoft word 2007+ file is Apache POI. In this libray, there is a class called XWPFDocument. The XWPFDocument class has the getAllPictures method that can extract all images in the file to store in a list.


extract images from microsoft word file

WordImageExtractor source code:

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class WordImageExtractor{
public static void main(String[] args){

selectwORD();

}

//allow office word file selection for extracting
public static void selectwORD(){

JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX","docx");
    chooser.setFileFilter(filter);
    chooser.setMultiSelectionEnabled(false);
    int returnVal = chooser.showOpenDialog(null);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
    File file=chooser.getSelectedFile();
    System.out.println("Please wait...");  
    extractImages(file.toString());
    System.out.println("Extraction complete");
           }

     
}
public static void extractImages(String src){
try{

//create file inputstream to read from a binary file
FileInputStream fs=new FileInputStream(src);
//create office word 2007+ document object to wrap the word file
XWPFDocument docx=new XWPFDocument(fs);
//get all images from the document and store them in the list piclist
List<XWPFPictureData> piclist=docx.getAllPictures();
//traverse through the list and write each image to a file
Iterator<XWPFPictureData> iterator=piclist.iterator();
int i=0;
while(iterator.hasNext()){
XWPFPictureData pic=iterator.next();
byte[] bytepic=pic.getData();
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytepic));
        ImageIO.write(imag, "jpg", new File("D:/imagefromword"+i+".jpg"));
        i++;
}

}catch(Exception e){System.exit(-1);}

}



}

In the code above, the JFileChooser is used to display a file dialog that the users can easily browse for a Microsoft Word file. Once, the path of the file is obtained, the extracting image process can start. The FileInputStream class reads the byte data of the Microsoft Word file. To get images from the original Microsoft Word file, firstly you need to construct a Microsoft Word document object by using the  XWPFDocument and pass the FileInputStream object to its constructor. Once you have document object, it seems like the original Microsoft Word file now is in you hand so you can do somethings with it. To get the images from the document, you will use the getAllPictures method. This method returns a lit of XWPFPictureData objects. Each XWPFPictureData object refer to an image. You can read all bytes from the XWPFPictureData object by using the getData. When you have the byte array of the image, you can construct the BufferedImage object from it. Then use the write method of the ImageIO class to write the image out to a file.
compass app flashLight app
compass app flashLight app