Java textfile I/O problem - java

I have to make a torpedo game for school with a toplist for it. I want to store it in a folder structure near the JAR: /Torpedo/local/toplist/top_i.dat, where the i is the place of that score. The files will be created at the first start of the program with this call:
File f;
f = new File(Toplist.toplistPath+"/top_1.dat");
if(!f.exists()){
Toplist.makeToplist();
}
Here is the toplist class:
package main;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.prefs.Preferences;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class Toplist {
static String toplistPath = "./Torpedo/local/toplist"; //I know it won't work this easily, it's only to get you the idea
public static JFrame toplistWindow = new JFrame("Torpedó - [TOPLISTA]");
public static JTextArea toplist = new JTextArea("");
static StringBuffer toplistData = new StringBuffer(3000);
public Toplist() {
toplistWindow.setSize(500, 400);
toplistWindow.setLocationRelativeTo(null);
toplistWindow.setResizable(false);
getToplist();
toplist.setSize(400, 400);
toplist.setLocation(0, 100);
toplist.setColumns(5);
toplist.setText(toplistData.toString());
toplist.setEditable(false);
toplist.setBackground(Color.WHITE);
toplistWindow.setLayout(null);
toplistWindow.setVisible(true);
}
public Toplist(Player winner) {
//this is to be done yet, this will set the toplist at first and then display it
toplistWindow.setLayout(null);
toplistWindow.setVisible(true);
}
/**
* Creates a new toplist
*/
public static void makeToplist(){
new File(toplistPath).mkdir();
for(int i = 1; i <= 10; i++){
File f = new File(toplistPath+"/top_"+i+".dat");
try {
f.createNewFile();
} catch (IOException e) {
JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista létrehozása", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* If the score is a top score it inserts it into the list
*
* #param score - the score to be checked
*/
public static void setToplist(int score, Player winner){
BufferedReader input = null;
PrintWriter output = null;
int topscore;
for(int i = 1; i <= 10; i++){
try {
input = new BufferedReader(new FileReader(toplistPath+"/top_"+i+",dat"));
String s;
topscore = Integer.parseInt(input.readLine());
if(score > topscore){
for(int j = 9; j >= i; j--){
input = new BufferedReader(new FileReader(toplistPath+"/top_"+j+".dat"));
output = new PrintWriter(new FileWriter(toplistPath+"/top_"+(j+1)+".dat"));
while ((s = input.readLine()) != null) {
output.println(s);
}
}
output = new PrintWriter(new FileWriter(toplistPath+"/top_"+i+".dat"));
output.println(score);
output.println(winner.name);
if(winner.isLocal){
output.println(Torpedo.session.remote.name);
}else{
output.println(Torpedo.session.remote.name);
}
output.println(Torpedo.session.mapName);
output.println(DateUtils.now());
break;
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista frissítése", "Error", JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista frissítése", "Error", JOptionPane.ERROR_MESSAGE);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista frissítése", "Error", JOptionPane.ERROR_MESSAGE);
}
}
if (output != null) {
output.close();
}
}
}
}
/**
* This loads the toplist into the buffer
*/
public static void getToplist(){
BufferedReader input = null;
toplistData = null;
String s;
for(int i = 1; i <= 10; i++){
try {
input = new BufferedReader(new FileReader(toplistPath+"/top_"+i+".dat"));
while((s = input.readLine()) != null){
toplistData.append(s);
toplistData.append('\t');
}
toplistData.append('\n');
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista betöltése", "Error", JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista betöltése", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
*
* #author http://www.rgagnon.com/javadetails/java-0106.html
*
*/
public static class DateUtils {
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
}
}
The problem is, that it can't access any of the files. I've tried adding them to the classpath and at least six different variations of file/path handling I found online but nothing worked.
Could anyone tell me what do I do wrong?
Thank you.

When you dealing with files, the path is relative to where you execute the application. When running it from eclipse, the base path is the project folder.
What you would normally do if the file doesn't exist is calling mkdirs() on the parent to create the folder hierarchy, then create the file.

Related

Java getting input from USB Barcode scanner

I have Honeywell USB barcode scanner. I want to read input of barcode scanner by using Java code.
I got solution by below code but i dont want to use any gui.
import java.awt.AWTEvent;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class BarcodeScaner extends JFrame {
private static String strBarcode = "";
private static JTextField jtBarcode = new JTextField(25);
public BarcodeScaner() {
getContentPane().setLayout(new FlowLayout());
getContentPane().add(new JLabel("Capture barcode "));
getContentPane().add(jtBarcode);
}
public static void main(String[] args) {
BarcodeScaner br = new BarcodeScaner();
readBarCode();
br.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
br.setVisible(true);
br.pack();
}
private static void readBarCode() {
// start of listening for barcode events
Toolkit.getDefaultToolkit().addAWTEventListener(new BarcodeAwareAWTEventListener(new BarcodeCapturedListener() {
#Override
public void barcodeCaptured(String barcode) {
strBarcode = barcode;
System.out.println("====="+barcode);
jtBarcode.setText(strBarcode);
}
}), AWTEvent.KEY_EVENT_MASK);
// end of listening for barcode events
}
}
In above code i have to focus on textbox then only i get scanned value.
I have search in stackoverflow but i didnt get any specific solution.
I also try this below code but still serialEvent is not execute.
package scanhandler;
import java.awt.AWTException;
import java.awt.Robot;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Enumeration;
import java.util.Properties;
import java.util.TooManyListenersException;
import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;
public class ScanHandler implements Runnable, SerialPortEventListener {
private static CommPortIdentifier myCommPortIdentifier;
private static Enumeration portList;
private static String TimeStamp;
private static String driverClass;
private static String connectionString;
private static String comPort;
private Connection myConnection;
private InputStream myInputStream;
private Robot myRobot;
private SerialPort mySerialPort;
private Thread myThread;
public ScanHandler() {
// open serial port
try {
TimeStamp = new java.util.Date().toString();
mySerialPort = (SerialPort) myCommPortIdentifier.open("ComControl", 2000);
//System.out.println(TimeStamp + ": " + myCommPortIdentifier.getName() + " opened for scanner input");
} catch (PortInUseException e) {
e.printStackTrace();
}
// get serial input stream
try {
myInputStream = mySerialPort.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
// add an event listener on the port
try {
mySerialPort.addEventListener(this);
} catch (TooManyListenersException e) {
e.printStackTrace();
}
mySerialPort.notifyOnDataAvailable(true);
// set up the serial port properties
try {
mySerialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
mySerialPort.setDTR(false);
mySerialPort.setRTS(false);
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
}
// make a robot to pass keyboard data
try {
myRobot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
// create the thread
myThread = new Thread(this);
myThread.start();
}
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
// on scan
public void serialEvent(SerialPortEvent event) {
if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
StringBuilder myStringBuilder = new StringBuilder();
int c;
try {
// append the scanned data onto a string builder
while ((c = myInputStream.read()) != 10){
if (c != 13) myStringBuilder.append((char) c);
}
// send to keyboard buffer if it the barcode doesn't start with '5'
if (myStringBuilder.charAt(0) != '5') {
for (int i = 0; i < myStringBuilder.length(); i++) {
myRobot.keyPress((int) myStringBuilder.charAt(i));
myRobot.keyRelease((int) myStringBuilder.charAt(i));
}
// here's the scanned barcode as a variable!
} else {
TimeStamp = new java.util.Date().toString();
System.out.println(TimeStamp + ": scanned input received:" + myStringBuilder.toString());
}
// close the input stream
myInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// read ScanHandler properties
Properties myProperties = new Properties();
try {
myProperties.load(new FileInputStream("config.properties"));
comPort = myProperties.getProperty("ScanHandler.comPort");
} catch (IOException e) {
e.printStackTrace();
}
try {
// get our pre-defined COM port
myCommPortIdentifier = CommPortIdentifier.getPortIdentifier(comPort);
ScanHandler reader = new ScanHandler();
} catch (Exception e) {
TimeStamp = new java.util.Date().toString();
System.out.println(TimeStamp + ": " + comPort + " " + myCommPortIdentifier);
System.out.println(TimeStamp + ": msg1 - " + e);
}
};
}
Please set the scanner to USB Serial mode by using the setting barcode stated in the user's guide.
Then install the serial port device driver of the OS of the machine to which the scanner is connected.
Then you can open the serial port and send commands to the scanner and receive barcode data.

Using File Dialogue Box Rather than FilePath Java

New to Java - I am trying to import a .txt file containing integers.
Eventually I want to import the integers into an arraylist and then create a frequency distribution and calculate the average.
Currently I am struggling to use the file dialogue box which is my end goal. I can import the .txt using the file path in my code shown. If any one could help me out with how to use the dialogue box instead it would be greatly appreciated!
import java.io.*;
import java.util.*;
public class Distribution {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Enter a complete file path to file you would like to open:");
String fileName = input.nextLine();
File inFile = new File(fileName);
FileReader ins = null;
try {
ins = new FileReader(inFile);
int ch;
while ((ch = ins.read()) != -1) {
System.out.print((char) ch);
}
}
catch (Exception e) {
System.out.println(e);
}
finally {
try {
ins.close();
}
catch (Exception e) {
}
}
} // main end
}
Well, It's simple and easy.
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
class DistributionUI {
public static void main(String[] args) {
System.out.println("Enter a complete file path to file you would like to open:");
final JFileChooser fchooser = new JFileChooser() {
private static final long serialVersionUID = 1L;
public void approveSelection() {
File inFile = getSelectedFile();
if (inFile.exists() ) {
FileReader ins = null;
try {
ins = new FileReader(inFile);
int ch;
while ((ch = ins.read()) != -1) {
System.out.print((char) ch);
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
ins.close();
} catch (Exception e) {
}
}
}
super.approveSelection();
}
};
fchooser.setCurrentDirectory(new File("."));
fchooser.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter("my file", "txt");
fchooser.addChoosableFileFilter(filter);
fchooser.showOpenDialog(null);
} // main end
}

Parallel Read and write application in java

I am developing an application in java where i am using a shared LinkedBlocking Queue and i am creating multiple threads for reading and writing it. I have created the code as below but i am unable to get the desired result.
For result i am using a shared file which is being written by both the threads (read and write one).
Please tell me whats wrong in my code:
Message Reader.java
package com.aohandling.messagereader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.aohandling.messagequeue.MessageQueue;
public class MessageReader implements Runnable
{
public static BufferedWriter out;
public static void init()
{
file = new File("AOHandle.txt");
try
{
out = new BufferedWriter(new FileWriter(file, true));
System.out.println("Init ");
}
catch (IOException e)
{
e.printStackTrace();
}
}
static File file = null;
public void run()
{
while (true)
{
try
{
SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
String s = MessageQueue.getMessageQueue().poll();
if (s != null)
{
out.write("queue - " + MessageQueue.getMessageQueue().poll() + "---" + ft.format(new Date()) + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
MessageWriter.java
package com.aohandling.writer;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.aohandling.messagequeue.MessageQueue;
import com.aohandling.messagereader.MessageReader;
public class MessageWriter implements Runnable
{
int n;
private int messageSequence;
public MessageWriter(int messageSequence)
{
this.messageSequence = messageSequence;
}
public void run()
{
try
{
SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
MessageReader.out.append("Writing----AO - " + this.messageSequence + "-----" + ft.format(new Date()) + "\n");
MessageQueue.getMessageQueue().put("AO " + this.messageSequence);
}
catch (IOException | InterruptedException e)
{
e.printStackTrace();
}
}
}
MessageQueue.java
package com.aohandling.messagequeue;
import java.util.concurrent.LinkedBlockingQueue;
public class MessageQueue {
private static LinkedBlockingQueue<String> messageQueue = new LinkedBlockingQueue<String>();
public static LinkedBlockingQueue<String> getMessageQueue() {
return MessageQueue.messageQueue;
}
public static void setMessageQueue(LinkedBlockingQueue<String> messageQueue) {
MessageQueue.messageQueue = messageQueue;
}
}
TestAOHandlingRead.java
package com.aohandling.main;
import com.aohandling.messagereader.MessageReader;
import com.aohandling.writer.MessageWriter;
public class TestAOHandlingRead
{
/**
* #param args
*/
public static void main(String[] args)
{
MessageReader.init();
for (int i = 0; i <= 200; i++)
{
Thread readThread = new Thread(new MessageReader());
readThread.start();
}
write();
}
public static void write()
{
for (int i = 0; i <= 20; i++)
{
if (i % 2 == 0)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
Thread writeThread = new Thread(new MessageWriter(i));
writeThread.start();
}
}
}
TestAOHandlingWrite.java
package com.aohandling.main;
import java.util.concurrent.atomic.AtomicInteger;
import com.aohandling.writer.MessageWriter;
public class TestAOHandlingWrite {
int count = 0;
public int getCount()
{
return count;
}
/**
* #param args
*/
public static void main(String[] args) {
// MessageWriter.init();
for (int i=0; i<= 20; i++) {
if (i%2 ==0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Thread writeThread = new Thread(new MessageWriter(i));
writeThread.start();
}
}
}
I suggest that you will use a FileChannel, since File channels are safe for use by multiple concurrent threads. In addition I refactored your code, the channel to your file will be created once, during the the first load of MessageReader class by the class loader.
public class MessageReader implements Runnable {
private static FileChannel channel;
static {
try {
System.out.println("Init ");
FileOutputStream fileOutputStream = new FileOutputStream(
"AOHandle.txt", true);
FileChannel channel = fileOutputStream.getChannel();
System.out.println("Init ");
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
FileLock fileLock = null;
try {
SimpleDateFormat ft = new SimpleDateFormat(
"E yyyy.MM.dd 'at' hh:mm:ss a zzz");
String s = MessageQueue.getMessageQueue().poll();
if (s != null) {
String message = "queue - "
+ MessageQueue.getMessageQueue().poll() + "---"
+ ft.format(new Date()) + "\n";
fileLock = channel.lock();
channel.write(ByteBuffer.wrap(message.getBytes()));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileLock != null) {
fileLock.release();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
The best practice is to open a channel to a file in one place and share him between your threads, since in your code no one closes the file.

While loop not updating variable defined by user

So, I have two classes.
main class:
package guiprojj;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import guiprojj.gui;
import javax.swing.JFrame;
#SuppressWarnings("unused")
public class Test {
public static String movie;
public static String line;
public static void main(String args[]) throws IOException {
BufferedReader rd;
OutputStreamWriter wr;
//Scanner s = new Scanner(System.in);
//System.out.println("Enter input:");
//movie = s.nextLine();
//movie = movie.replaceAll(" ", "%20");
while (movie != null)
{
try {
URL url = new URL("http://www.imdbapi.com/?i=&t=" + movie);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
// Get the response
rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
line = rd.readLine();
if (line != null) {
System.out.println(line);
} else {
System.out.println("Sorry! That's not a valid URL.");
}
} catch (UnknownHostException codeyellow) {
System.err.println("Caught UnknownHostException: " + codeyellow.getMessage());
}
catch (IOException e)
{
System.out.println("Caught IOException:" + e.getMessage());
}
}
}
}
gui class:
package guiprojj;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class gui {
public static void main(String[] args)
{
JFrame maingui = new JFrame("Gui");
JPanel pangui = new JPanel();
JButton enter = new JButton("Enter");
JLabel movieinfo = new JLabel(Test.line);
final JTextField movietext = new JTextField(16);
maingui.add(pangui);
pangui.add(movietext);
pangui.add(enter);
pangui.add (movieinfo);
maingui.setVisible(true);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maingui.pack();
enter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
Test.movie = movietext.getText();
System.out.println(Test.movie);
}
});
}
}
What I am writing is a program that outputs the movie data from imbd after you enter it in the box, and I am running into an issue.
When I type in the movie, and press enter, it still shows as null and doesn't seem to be outputting the data from the api I am using.
public class Test {
public static String getMovieInfo(String movie) {
BufferedReader rd;
OutputStreamWriter wr;
//Scanner s = new Scanner(System.in);
//System.out.println("Enter input:");
//movie = s.nextLine();
//movie = movie.replaceAll(" ", "%20");
if (movie != null)
{
try {
URL url = new URL("http://www.imdbapi.com/?i=&t=" + movie);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
// Get the response
rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = rd.readLine();
if (line != null) {
return line;
} else {
return "Sorry! That's not a valid URL.";
}
} catch (UnknownHostException codeyellow) {
System.err.println("Caught UnknownHostException: " + codeyellow.getMessage());
}
catch (IOException e)
{
System.out.println("Caught IOException:" + e.getMessage());
}
}
else
{
return "passed parameter is null!";
}
return "an error occured, see console!";
}
}
I've rewritten your Test-class. Renamed main-method, added return-statements (String) and removed the while-loop. Try to avoid multiple main(String[] args)-methods in one project, else your IDE could launch the "wrong" one, if your context switches.
I did not test it, but now you should be able to call Test.getMovieInfo("movie-name") from your gui-class to get the info.
(nethertheless this code should be refactored ;))

Download file from URL to FOLDER

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) {
}
}
}*/
}

Categories