Currently im trying to load a qrcode in buffer so it would display on the spot.
This is my current revision for the code.
package wallettemplate;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import static wallettemplate.MainPage.kit;
public class BackEnd{
public static final String QR_CODE_IMAGE_PATH = "./MyQRCode.png";
public static String decodeQRCode(File qrCodeimage) throws IOException {
BufferedImage bufferedImage = ImageIO.read(qrCodeimage);
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
Result result = new MultiFormatReader().decode(bitmap);
return result.getText();
} catch (NotFoundException e) {
System.out.println("There is no QR code in the image");
return null;
}
}
public static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
public static String gbal(){
String balance = kit.wallet().getBalance().toFriendlyString();
return balance;
}
public static String purchase(double amount){
String text;
try {
generateQRCodeImage("bitcoin:"+kit.wallet().currentReceiveAddress().toString()+"?amount="+String.format("%.7f",amount), 20, 20, QR_CODE_IMAGE_PATH);
text = "QR Code generated. - "+kit.wallet().currentReceiveAddress().toString();
} catch (WriterException e) {
text = "Could not generate QR Code, WriterException :: " + e.getMessage();
} catch (IOException e) {
text = "Could not generate QR Code, IOException :: " + e.getMessage();
}
return text;
}
public static String refund(){
String text;
try {
File file = new File(QR_CODE_IMAGE_PATH);
String decodedText = decodeQRCode(file);
if(decodedText == null) {
text = "No QR Code found in the image";
} else {
//text = "Decoded text = " + decodedText + " and the amount is "+value;
String[] parts = decodedText.split(":");
String[] amnt = parts[1].split("\\?");
String[] finn = amnt[1].split("=");
text = "Type: " + parts[0] + "\nAddress: " + amnt[0] + "\nAmount: " + finn[1];
String[] linkparam = {parts[0],amnt[0],finn[1]};
text = text + "\n" + linkparam[0] + " - " + linkparam[1] + " - " + linkparam[2];
}
} catch (IOException e) {
text = "Could not decode QR Code, IOException :: " + e.getMessage();
}
return text;
}
}
Above is the class that deals with all functions i need.
When i load the next contentpane it doesnt load up the qrcode that gets stored. But when i shut the program down and load it up, put in a new amount it reads the qrcode from last time.
I call it with this.
btnConfirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
BackEnd.purchase(Double.parseDouble(lblfinal.getText()));
parentForm.showPanel(MainPage.PPROCESS);
}
});
The qrcode gets generated fine no issues.
When i read it with an image inside a JLabel i use this code.
private void createUIComponents() {
ImageIcon imageIcon = new ImageIcon("MyQRCode.png");
Image image = imageIcon.getImage();
Image newimg = image.getScaledInstance(200, 200, java.awt.Image.SCALE_SMOOTH);
imageIcon = new ImageIcon(newimg);
lblQRCode = new JLabel(imageIcon);
}
These 2 segments are in different classes. How can i get it to read the CURRENT one i actually need?
Answer as follows.
public static BufferedImage getQRCodeImage(String amount) throws WriterException{
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode("bitcoin:"+kit.wallet().currentReceiveAddress().toString()+"?amount="+String.format("%.7f",Double.parseDouble(amount)), BarcodeFormat.QR_CODE, 200, 200);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
imageIcon.setImage(BackEnd.getQRCodeImage(cost));
lblQRCode.setIcon(imageIcon);
Related
I need to get byte[] array from a QR Code encoded into a BitMatrix. Here's my code:
// imports
import com.google.zxing.BarcodeFormat;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.DecoderResult;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.datamatrix.decoder.Decoder;
The function to generate QR Code:
public byte[] createQRCode() {
String qrCodeData = "Hello world";
String charset = "UTF-8";
BitMatrix matrix = null;
Writer writer = new QRCodeWriter();
try {
matrix = writer.encode(new String(qrCodeData.getBytes(charset), charset), BarcodeFormat.QR_CODE, qrCodeheight, qrCodewidth);
} catch (UnsupportedEncodingException e) {
return;
}
catch (WriterException e) {
return;
}
DecoderResult decoderResult = null;
try {
decoderResult = new Decoder().decode(matrix);
} catch (ChecksumException e) {
return;
} catch (FormatException e) {
// Always this exception is throwed
}
byte[] cmd = decoderResult.getRawBytes();`
return cmd;
}
Always the execution stop on FormatException, even the parameter on Decode().decode() requested is BitMatrix.
Someone can tell me what's wrong or show me other way to get the QR Code byte array?
I found the solution using a library to decode Bitmap:
https://github.com/imrankst1221/Thermal-Printer-in-Android
Function to encode String into QR Code Bitmap:
public Bitmap encodeToQrCode(String text, int width, int height){
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = null;
try {
matrix = writer.encode(text, BarcodeFormat.QR_CODE, width, height);
} catch (WriterException ex) {
//
}
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++){
for (int y = 0; y < height; y++){
bmp.setPixel(x, y, matrix.get(x,y) ? Color.BLACK : Color.WHITE);
}
}
return bmp;
}
Then I decode bitmap to bytes using Utils from the found library:
try {
Bitmap bmp = encodeToQrCode("Hello world", 200, 200);
if (bmp != null ) {
byte[] command = Utils.decodeBitmap(bmp);
BluetoothPrintDriver.BT_Write(command);
} else {
Log.e("Print Photo error", "file not found");
}
} catch (Exception e) {
e.printStackTrace();
Log.e("PrintTools", "file not found");
}
I'm coding a swing App. Here the tasks are to download the file from a given URL and then get the counts of them. The program works with no issues/errors.
The problem is I've a testarea in my frame, when file 1 is downloaded I want the text area to show downloaded file 1 and when file 2 is done downloaded file 1 and so on...
Currently in my program the message is displayed but all at once. I mean if I've 10 files, it shows.
downloaded file 1
downloaded file 2
.
.
.
.
.
downloaded file 10
But this is shown only after all the 10 files are downloaded. To see if there is any other problem, I've added sysout just below the textarea code. And to my surprise, sysouts are printed 10 times, I mean each time a file is processed, this is triggered, but the textarea is appended with all the data at a time.
Below are my codes.
GuiForPDFs
import java.awt.BorderLayout;
public class GuiForPDFs extends JFrame {
private JPanel contentPane;
private JTextField srcTextField;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GuiForPDFs frame = new GuiForPDFs();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
FileDownloadTest downloadTest = new FileDownloadTest();
public GuiForPDFs() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 552, 358);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
srcTextField = new JTextField();
srcTextField.setBounds(10, 26, 399, 20);
contentPane.add(srcTextField);
srcTextField.setColumns(10);
JButton srcBtn = new JButton("Source Excel");
srcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fChoose = new JFileChooser();
if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath());
} else {
System.out.println("No Selection");
}
}
});
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setBounds(10, 106, 516, 203);
contentPane.add(textArea);
srcBtn.setBounds(419, 25, 107, 23);
contentPane.add(srcBtn);
JButton dNcButton = new JButton("Process");
dNcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
downloadTest.fileDownloadTest(srcTextField.getText(), textArea);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
dNcButton.setBounds(212, 70, 89, 23);
contentPane.add(dNcButton);
}
}
FileDownloadTest
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JTextArea;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class FileDownloadTest {
public void fileDownloadTest(String src, JTextArea textArea) throws IOException, InterruptedException {
String path = src;
FileInputStream fin = new FileInputStream(new File(path));
XSSFWorkbook workbook = new XSSFWorkbook(fin);
XSSFSheet sheet = workbook.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
System.out.println("rows are " + rows);
XSSFCell cell;
// Make sure that this directory exists
String dirName = src.substring(0, src.lastIndexOf("\\"));
File f = new File(dirName);
if (!f.exists()) {
f.mkdir();
}
System.out.println(f.getAbsolutePath() + " is Directory Name " + src + " is the file");
for (int i = 1; i < rows; i++) {
XSSFCell url = sheet.getRow(i).getCell(0);
String URLString = url.toString();
cell = sheet.getRow(i).getCell(7);
String fileName = URLString.substring(URLString.lastIndexOf("/") + 1);
int pageNumbers = downloadFiles(dirName, url.toString().replace("http", "https"));
if (cell == null) {
cell = sheet.getRow(i).createCell(1);
}
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(pageNumbers);
FileOutputStream fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
textArea.append("downloaded " + fileName + "\n");
System.out.println("Done");
}
workbook.close();
fin.close();
}
public static int downloadFiles(String dirName, String urlString) {
System.out.println("Downloading \'" + urlString + "\' PDF document...");
String fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
System.out.println(fileName + " is file name");
try {
saveFileFromUrlWithJavaIO(dirName + "\\" + fileName, urlString);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Downloaded \'" + urlString + "\' PDF document...");
int pageNumber = 0;
try {
pageNumber = getNoOfPages(dirName + "\\" + fileName);
} catch (IOException e) {
e.printStackTrace();
}
return pageNumber;
}
public static int getNoOfPages(String fileName) throws IOException {
PDDocument document = PDDocument.load(new File(fileName));
int numberOfPages = document.getNumberOfPages();
return numberOfPages;
}
public static void saveFileFromUrlWithJavaIO(String fileName, String fileUrl)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(fileUrl).openStream());
fout = new FileOutputStream(fileName);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null)
in.close();
if (fout != null)
fout.close();
}
}
public static void saveFileFromUrlWithCommonsIO(String fileName, String fileUrl)
throws MalformedURLException, IOException {
FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
}
}
please let me know How can I fix this.
Thanks
The above comments are correct, you are on the EDT when adding text to the TextArea. This is because you are calling downloadTest.fileDownloadTest from the dNcButton ActionListener implementation.
It's good practice to get off the EDT is you have a long running operation to perform, and downloading a file is often given as as example of the sort of thing you don't want to do on the EDT.
There are lots of resources online as to how to get off the EDT, including many on this great site;
On Event Dispatch Thread---want to get off of it
Make thread run on non EDT (event dispatch thread) thread from EDT
As with the other comments, you need to keep only UI related tasks on the EDT. Otherwise if your user is downloading 100 files the UI will lock up until the download task is finished. SwingWorker is the perfect class to do this for Swing applications. Here is a quick example:
// Run your FileDownloadTest inside a SwingWorker
// or have the class extend SwingWorker
new SwingWorker<Void, String>() {
#Override
protected Void doInBackground() throws Exception {
//Perform downloading here (done off the EDT)
//Call publish(downloadedFileName) to be sent to the process method()
return null;
}
#Override
protected void process(List<String> chunks) {
// Modify textArea (done on the EDT)
StringBuilder downloadedFiles = new StringBuilder();
for (String fileName : chunks) {
downloadedFiles.append("downloaded" + fileName + "\n");
}
textArea.setText(downloadedFiles);
}
#Override
protected void done() {
//Anything you want to happen after doInBackground() finishes
}
}.execute();
i have a program to show a static Google map after inputting data but when i want to refresh my map the JLabel doesn't change. here is my code for the buttons one just clears the map:
JButton btnMakeMap = new JButton("Make map");
btnMakeMap.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Map map = new Map(txfPlace.getText(), cmbMarkerName.getSelectedItem().toString().charAt(0), cmbMrkColour.getSelectedItem().toString(), Integer.parseInt(cmbZoom.getSelectedItem().toString()),
cmbMrkSize.getSelectedItem().toString(), chbCenter.isSelected(), cmbType.getSelectedItem().toString());
if(chbCenter.isSelected()){
map.genMarker();
map.genURlWcenter();
}else{
map.genMarker();
map.genURl();
}
lblMap.setIcon(null);
map.genimage();
ImageIcon im = new ImageIcon("map.jpg");
lblMap.setIcon(im);
}
});
btnMakeMap.setBounds(235, 146, 117, 49);
pnlSettings.add(btnMakeMap);
JButton btnRefresh = new JButton("clear map");
btnRefresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// Map map = new Map(txfPlace.getText(), cmbMarkerName.getSelectedItem().toString().charAt(0), cmbMrkColour.getSelectedItem().toString(), Integer.parseInt(cmbZoom.getSelectedItem().toString()),
// cmbMrkSize.getSelectedItem().toString(), chbCenter.isSelected(), cmbType.getSelectedItem().toString());
lblMap.setIcon(null);
// map.genimage();
// ImageIcon im = new ImageIcon("map.gif");
// lblMap.setIcon(im);
//
}
});
btnRefresh.setBounds(406, 172, 89, 23);
pnlSettings.add(btnRefresh);
this is the code for the class it uses:
package com.mymaps;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.apache.http.HttpConnection;
import org.jboss.remoting.transport.Connector;
public class Map {
private String URl = "https://maps.googleapis.com/maps/api/staticmap?";
private int Zoom = 1;
private String Location = "";
private String markColor = "";
private String Marker = "";
private char markName;
private String markSize = "";
private String mapSize = "&size=400x400";
private boolean wantMarkeratCenter = false;
private String mapType = "maptype=";
public Map(String location, char name, String colour, int zoom,
String mrksize, boolean center, String type) {
Location = location;
markName = name;
markColor = markColor + colour;
markSize = mrksize;
Zoom = zoom;
wantMarkeratCenter = center;
mapType = mapType + type;
fixLocation();
// if (wantMarkeratCenter){//check if the user wants a marker at the
// center
// genMarker();
// genURlWcenter();
// }else{
// if(!wantMarkeratCenter){
// genMarker();
// genURl();
// }
// }
}
public boolean validateURl() {// validates URl length
boolean isValid = false;
if (URl.length() < 0 || URl.length() > 2048) {
isValid = true;
} else {
isValid = false;// y? just because
}
return isValid;
}
public void genURl() {// creates the URl for use
if (wantsSize()) {
URl = URl + mapSize + "&zoom=" + Zoom + "&" + mapType + "&"
+ Marker;
} else {
URl = URl + "&" + mapType + Marker;
}
}
public void genURlWcenter() {// generates URl with the center on the
// location point
String loc = Location.replace('+', ',');
if (wantsSize()) {
URl = URl + "center=" + loc + mapSize + "&" + mapType + "&" + Marker;
} else {
URl = URl;
}
}
public void genMarker() {// generates the marker
String name = "" + markName;
Marker = "markers=color:" + markColor + "|label:" + name.toUpperCase()
+ "|" + Location;
}
private boolean wantsSize() {// checks if the user wanted a size or not
// based on the var size
boolean wantSize = false;
if (mapSize.length() != 0) {
wantSize = true;
}
return wantSize;
}
public String getMarker() {
return Marker;
}
public String getURl() {
return URl;
}
public void genimage() {
URL url;
try {
url = new URL(URl);
System.out.println(url);
System.out.println();
InputStream is = url.openStream();
OutputStream os = new FileOutputStream("map.jpg");
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void fixLocation() {
Scanner sc = new Scanner(Location);
String temp = "";
while (sc.hasNext()) {
temp = temp + sc.next() + "+";
}
temp = temp.substring(0, temp.length() - 1);
Location = temp;
sc.close();
}
public String getLocation() {
return Location;
}
public ImageIcon getImage() {
ImageIcon im = new ImageIcon("map..jpg");
return im;
}
}
this is a runnable version of the code here
lblMap.setIcon(null);
map.genimage();
ImageIcon im = new ImageIcon("map.jpg");
lblMap.setIcon(im);
Looks like you are creating the map.jpg and binding it to label when you want to refresh. with this code, do you still see old image after refresh? Did you verified that the map.jpg is latest? If yes then could be issue with OS paging and OS still returning the old file when JVM asked for it. You can solve this by generating unique file name everytime on refresh
I am using icepdf to convert the pdf to image. Here is the code.
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
public class PageCapture {
private static ArrayList<File> fileNames = new ArrayList<File>();
public static void main(String[] args) {
// Get a file from the command line to open
String filePath = "example.pdf";
// open the file
Document document = new Document();
RenderedImage rendImages = null;
File file = null;
BufferedImage bi = null;
int height = 0, width = 0, i = 0, x = 0, y = 0;
try {
document.setFile(filePath);
} catch (PDFException ex) {
System.out.println("Error parsing PDF document " + ex);
} catch (PDFSecurityException ex) {
System.out.println("Error encryption not supported " + ex);
} catch (FileNotFoundException ex) {
System.out.println("Error file not found " + ex);
} catch (IOException ex) {
System.out.println("Error IOException " + ex);
}
// save page captures to file.
float scale = 5.0f;
float rotation = 0f;
// Paint each pages content to an image and
// write the image to file
for (i = 0; i < document.getNumberOfPages(); i++) {
BufferedImage image = (BufferedImage) document.getPageImage(i,
GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX,
rotation, scale);
height = image.getHeight();
width = image.getWidth();
rendImages = image;
file = new File("C:/INC/imageCapture1_" + i + ".tif");
try {
fileNames.add(file);
ImageIO.write(rendImages, "tif", file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
image.flush();
}
try {
BufferedImage result = new BufferedImage(width, height * i, // work
// these
// out
BufferedImage.TYPE_INT_RGB);
Graphics g = result.getGraphics();
for (int j = 0; j < fileNames.size(); j++) {
bi = ImageIO.read(fileNames.get(j));
g.drawImage(bi, x, y, null);
y += height;
}
file = new File("C:/INC/imageCapture_new_.tif");
ImageIO.write(result, "tif", file);
} catch (IOException e) {
e.printStackTrace();
}
// clean up resources
document.dispose();
}
}
The above code is working fine for true type fonts but type3 fonts are not getting displayed in the image.
Can anyone tell how to convert the pdf with type3 fonts to image.
The above code generates each image for each pdf page. Is there anyway to generate single image for all the pdf pages.
The open source version of ICEpdf does not support Type 3 fonts. The PRO version does support Type 3 and can be licensed if needed.
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new
java.net.URL(args[1].toString()).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream("WorldEdit/schematics/"+args[2].toString());
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte data[] = new byte[1024];
while(in.read(data,0,1024)>=0)
{
bout.write(data);
}
bout.close();
in.close();
}
I want this to download a file from a url, and put it into a folder. This program will be in a folder named "plugins" where I want to put the downloaded file is in "plugins/WorldEdit/schematic".
Doesn't seem to work. Any suggestions?
in.read returns a number indicating how many bytes were actually read. You are ignoring that number and assuming 1024 bytes are read on each call.
If you are using Java 7, you can save a URL to a file this way:
try (InputStream in = new URL(args[1].toString()).openStream()) {
Files.copy(in, Paths.get("WorldEdit", "schematics", args[2].toString()));
}
In Java 6 (and 5 and 4), you can use channels:
FileChannel fileChannel = fos.getChannel();
ReadableByteChannel urlChannel = Channels.newChannel(
new URL(args[1].toString()).openStream());
fileChannel.transferFrom(urlChannel, 0, Long.MAX_VALUE);
You can refer the following program and edit according to your needs.
In this program url is fetching from a table in an html file using Jsoup to parse the html file and downloading into different folder..path of the folder I took from the table(table has 3 column filename,path,download link) .
Go to downloadFile(String urlString) method,there you can find the answer for your question
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author nudanesh
*/
public class URLDownload {
private Document doc;
String url = "", folder, file;
private final File sourceFile;
int i = 1;
int r = 1, c = 1;
int anchorCol = 3;
Library lib;
URLDownload() {
lib = new Library();
sourceFile = new File("Download.html");
try {
doc = Jsoup.parse(sourceFile, "UTF-8");
} catch (IOException ex) {
Logger.getLogger(URLDownload.class.getName()).log(Level.SEVERE, null, ex);
}
//Elements links = doc.select("a[href]");
Elements rows = doc.select("tr");
System.out.println("Size=" + rows.size());
for (Element row : rows) {
Elements cols = row.getElementsByTag("td");
c = 1;
for (Element col : cols) {
System.out.println("Row"+r);
if (c == 1) {
file = col.text();//System.out.println("File in main"+file);
} else if (c == 2) {
folder = col.text();//System.out.println("Folder in main"+folder);
} else {
try {
url = col.getElementsByTag("a").attr("href");
} catch (Exception e) {
System.out.print("-");
}
}
c++;
}
if (!url.equals("")) {
lib.setLocation(file,folder);
lib.downloadFile(url);
}
url = "";
i++;
r++;
}
}
public static void main(String arg[]) {
new URLDownload();
}
}
and following is the Library class file
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author nudanesh
*/
public class Library {
boolean downloaded = false;
Thread t;
int waitTime = 0;
String baseLoc = "";
int size = 1024, ByteWritten = 0;
URL url;
URLConnection uCon = null;
String folderLoc = "", file = "firstFile.csv";
File loc;
private OutputStream outStream;
private InputStream is=null;
private byte[] buf;
private int ByteRead;
private int FolderInUrl = 4;
private boolean rootFolder = true;
private File resultFile;
private FileOutputStream fileResult;
private XSSFWorkbook workbookResult;
private XSSFSheet sheetResult;
private int updateExcelRowNum = -1;
private int updateExcelColNum = -1;
String date;
private int waitLimit = 900000;
Library() {
/*System.out.print(Calendar.getInstance().toString());
Date d=new Date();
String date=d.toString();
System.out.println(date);*/
//t = new Thread(this);
// t.start();
date = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(Calendar.getInstance().getTime());
System.out.print(date);
baseLoc = date + "/";
WriteDataToExcel();
baseLoc += "Business Reports/";
createRowExcel(updateExcelRowNum);
updateRowColExcel(updateExcelRowNum, updateExcelColNum, "Report Name");
updateRowColExcel(updateExcelRowNum, updateExcelColNum, "Path");
updateRowColExcel(updateExcelRowNum, updateExcelColNum, "Status");
updateExcel();
}
public void setLocation(String a, String b) {
file = a;
file += ".csv";
folderLoc = baseLoc + getFolderPath(b);
// System.out.println("File Name: "+file);
// System.out.println("Folder loc: "+folderLoc);
}
public String getFolderPath(String b) {
String path = "";
try {
System.out.println("path" + b);
path = b;
// path = java.net.URLDecoder.decode(b, "UTF-8");
String p[] = path.split("/");
path = "";
for (int i = FolderInUrl; i < p.length - 1; i++) {
rootFolder = false;
p[i] = removeSpacesAtEnd(p[i]);
path = path + p[i] + "/";
}
} catch (Exception ex) {
Logger.getLogger(Library.class.getName()).log(Level.SEVERE, null, ex);
}
return path;
}
public void downloadFile(String urlString) {
// System.out.println("Started");
try {
url = new URL(urlString);
} catch (MalformedURLException ex) {
Logger.getLogger(Library.class.getName()).log(Level.SEVERE, null, ex);
}
try {
loc = new File(folderLoc);
if (!loc.exists()) {
loc.mkdirs();
}
outStream = new BufferedOutputStream(new FileOutputStream(folderLoc + file));
uCon = url.openConnection();
uCon.setReadTimeout(waitLimit);
is = uCon.getInputStream();
downloaded=true;
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
System.out.println("while executing" + ByteRead);
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
//System.out.println("Downloaded" + ByteWritten);
resetCounters();
createRowExcel(updateExcelRowNum);
updateRowColExcel(updateExcelRowNum, updateExcelColNum, file);
updateRowColExcel(updateExcelRowNum, updateExcelColNum, folderLoc);
if (ByteWritten < 1000) {
updateRowColExcel(updateExcelRowNum, updateExcelColNum, "Downloaded ");
} else {
updateRowColExcel(updateExcelRowNum, updateExcelColNum, "Downloaded ");
}
updateExcel();
} catch (Exception e) {
System.out.println("error catch" + e);
resetCounters();
createRowExcel(updateExcelRowNum);
updateRowColExcel(updateExcelRowNum, updateExcelColNum, file);
updateRowColExcel(updateExcelRowNum, updateExcelColNum, folderLoc);
updateRowColExcel(updateExcelRowNum, updateExcelColNum, "Rejected the Download after waiting " + (waitLimit / 60000) + " minutes");
updateExcel();
waitTime = 0;
} finally {
try {
System.out.println("Error in streams");
if(downloaded)
is.close();
outStream.close();
downloaded= false;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void moveToFolder(String reportName, String path) {
try {
File repo = new File(folderLoc + "/" + reportName + ".csv");
path = folderLoc + "/" + path;
File pathFolder = new File(path);
if (!pathFolder.exists()) {
pathFolder.mkdirs();
}
pathFolder = new File(path + reportName + ".csv");
System.out.println("Path=" + pathFolder.getAbsolutePath() + "\nReport path=" + repo.getAbsolutePath());
System.out.println("Source" + repo.getAbsolutePath());
//System.out.println("Status" + repo.renameTo(new File(pathFolder.getAbsolutePath())));
System.out.println("Status" + Files.move(repo.toPath(), new File(pathFolder.getAbsolutePath()).toPath(), REPLACE_EXISTING));
//Files.
} catch (Exception e) {
System.out.println("error while moving" + e);
}
}
public String changeSpecialCharacters(String report) {
report = report.replaceAll(":", "_");
return report;
}
public String removeSpacesAtEnd(String inputPath) {
for (int i = inputPath.length() - 1; i >= 0; i--) {
if (inputPath.charAt(i) != ' ') {
break;
} else {
System.out.println("Before string is" + inputPath);
inputPath = inputPath.substring(0, i);
System.out.println("AFter string is" + inputPath);
}
}
return inputPath;
}
public void WriteDataToExcel() {
try {
// file = new FileInputStream(new File("config.xlsx"));
// File resultFolder = new File("Results");
// if (resultFolder.exists()) {
// deleteDirectory(resultFolder);
// }
// resultFolder.mkdirs();
if (!new File(baseLoc).exists()) {
new File(baseLoc).mkdirs();
}
resultFile = new File(baseLoc + "Reports info " + date + ".xlsx");
System.out.println("Path" + resultFile.getAbsolutePath());
resultFile.createNewFile();
// rFilePath = resultFile.getAbsolutePath();
fileResult = new FileOutputStream(resultFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Get the workbook instance for XLS file
// System.out.println("file success");
XSSFWorkbook workbook = null;
try {
workbookResult = new XSSFWorkbook();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Opening the browser");
//Get first sheet from the workbook
sheetResult = workbookResult.createSheet();
//sheetResult.set
//Get iterator to all the rows in current sheet
//Get iterator to all cells of current row
//ar.add(folderLocation);
// ar.add(firefoxProfileLocation);
}
public void updateExcel() {
try {
//fileResult.close();
fileResult = new FileOutputStream(resultFile);
workbookResult.write(fileResult);
fileResult.close();
} catch (Exception e) {
System.out.println(e);
}
}
public void createRowExcel(int num) {
updateExcelRowNum++;
num = updateExcelRowNum;
sheetResult.createRow(num);
}
public void updateRowColExcel(int rnum, int cnum, String value) {
updateExcelColNum++;
cnum = updateExcelColNum;
sheetResult.getRow(rnum).createCell(cnum);
XSSFCell cell = sheetResult.getRow(rnum).getCell(cnum);
cell.setCellValue(value);
}
public void updateColumn(int rnum, int cnum, String value) {
XSSFCell cell = sheetResult.getRow(rnum).getCell(cnum);
cell.setCellValue(value);
}
public void resetCounters() {
updateExcelColNum = -1;
}
/* #Override
public void run() {
while (true) {
if (true) {
waitTime += 1000;
System.out.println(waitTime);
if (waitTime > waitLimit) {
try {
is.close();
outStream.close();
//downloaded=false;
// cancelDownload=true;
} catch (Exception ex) {
Logger.getLogger(Library.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}*/
}