accessing a local file (Java URL) - java

I'm trying to open a stream to a file on my PC and I'm trying to do it via URL (I know,It's just for leraning purposes)
this is what I'm doing:
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
public class URLTyper {
public static void main(String[] args) {
InputStream in=null;
try {
URL url=new URL("file://127.0.0.1/c:/haxlogs.txt");
// in=url.openStream();
URLConnection conn=url.openConnection();
conn.connect();
in=conn.getInputStream();
while (true) {
int read=in.read();
if (read==-1) break;
System.out.write(read);
}
}
catch (SocketTimeoutException e){
System.out.println("timed out");
}
catch (MalformedURLException e) {
System.out.println("URL not valid");
}
catch (IOException e) {
System.out.println("unable to get data");
}
}
}
It exits throwing an IOException ("unable to access data").. why is it not working? shouldn't it get to the file like an ordinary InputStream?
thanks

Related

How do I get try and catch to work in my code?

Goal: When calling on 'initializeDriver', I don't want to have to keep throwing an IOexception in another class.
How do I properly implement a "try" and "catch" to my code? here is my attempt, however, it's not working correctly. I have tried looking around but I may not be understanding it correctly.
Here is a link to my gitHub in case anyone wants to take a look: https://github.com/intuitive86/Sample_Driver_Test
package resources;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Base {
public WebDriver driver;
protected Properties dataProperties;
public WebDriver initializeDriver() throws IOException {
// Create global property file
dataProperties = new Properties();
InputStream dataPropertiesInputStream = null;
try{
InputStream = getClass().getClassLoader().getResourceAsStream("data.properties");
dataProperties.load(dataPropertiesInputStream);
} catch (IOException e) {
e.printStackTrace();
}
String browserName = dataProperties.getProperty("browser");
System.out.println(browserName);
if (browserName.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
} else if (browserName.equals("firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
Your question is not clear to me. As I understood, you need to hide the IOException which shows from another area.
try{
InputStream = getClass().getClassLoader().getResourceAsStream("data.properties");
dataProperties.load(dataPropertiesInputStream);
} catch (IOException e) {
e.printStackTrace();
}
Remove e.printStackTrace(); from catch block and provide some logger.
try{
InputStream = getClass().getClassLoader().getResourceAsStream("data.properties");
dataProperties.load(dataPropertiesInputStream);
} catch (IOException e) {
logger.error("I got IO exception, no need to worry, it's normal", e.getMessage());
}

No Action works after Enabling ServerSocket in JAVA

I have created a Server Socket and enabled it to listen to incoming streams.But after enabling the connection it should display a dialog Box showing message "Server Started" ,but it does not appear . I have noticed that after enabling the socket no code after that works. I have tried searching a lot about this but seem to find no suitable answer.Here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Server
{
public Server(int i1) throws Exception{
ServerSocket MySock=new ServerSocket(i1);//opening server socket
Socket Sock=MySock.accept();//listening to client enabled
JOptionPane.showMessageDialog(null, "Server Started");
}
public static void main(String[] args) {
try {
new Server(2005);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The problem is that ServerSocket.accept() is blocks until a connection is made..
So the JOptionPane.showMessageDialog(...) will not be executed until someone is connecting to the serversocket.
Here is a solution that handles the ServerSocket in a separate thread
import java.io.IOException;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.*;
public class Server
{
public Server(int i1) throws Exception{
Runnable serverTask = () -> {
try {
ServerSocket MySock=new ServerSocket(i1);//opening server socket
while (true) {
Socket Sock=MySock.accept();//listening to client enabled
System.out.println("Accept from " + Sock.getInetAddress());
}
} catch (IOException e) {
System.err.println("Accept failed.");
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(serverTask);
JOptionPane.showMessageDialog(null, "Server Started");
}
public static void main(String[] args) {
try {
new Server(2005);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

file cannot be deleted even after closing streams

I'm trying to open a file from a URL, copy it to a temporary file, and then delete the temporary file when processing work is done. However, I am unable to delete the file. I have tried closing all streams, I have tried deleting with both deleteOnExit() method and the Delete() method. This is an excel file which I am working with. When I am not using an excel file, or more particularly the Workbook object as shown in my code below, the file deletes just fine. As soon as I pass my file to the workbookFactory.create() method, my file cannot be deleted by the code.
Here's the code below:
public class URLtoFileWriting {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
static File destinationFile;
public static void getFile() throws IOException {
try {
// TODO code application logic here
URL fileURL = new URL("http://www.testURL.com/testfile.xlsx");
URLtoFileWriting.destinationFile = File.createTempFile("remotefile",".xlsx");
try {
URLConnection URLconnection = fileURL.openConnection();
InputStream inputStream = URLconnection.getInputStream();
FileOutputStream fileoutputStream = new FileOutputStream(URLtoFileWriting.destinationFile);
IOUtils.copy(inputStream, fileoutputStream);
Workbook wb = WorkbookFactory.create(URLtoFileWriting.destinationFile);
System.out.println(URLtoFileWriting.destinationFile.getAbsolutePath());
inputStream.close();
fileoutputStream.close();
System.out.println("Deleted testWB?!" + URLtoFileWriting.destinationFile.delete());
} catch (IOException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidFormatException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (MalformedURLException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
All the imports I am using:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
I suspect it has something to do with the workbookFactory.create() method, as deletion becomes impossible once I have passed the file to this method.
What am I doing wrong here?
UPDATE. I have come across a fix:
You can pass the File to a FileInputStream, and then pass this stream to the WorkbookFactory.Create() method.
Updated code below to reflect this:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class URLtoFileWriting {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
static File destinationFile;
public static void getFile() throws IOException {
try {
// TODO code application logic here
URL fileURL = new URL("http://www.testURL.com/testfile.xlsx");
URLtoFileWriting.destinationFile = File.createTempFile("remotefile",".xlsx");
try {
URLConnection URLconnection = fileURL.openConnection();
InputStream inputStream = URLconnection.getInputStream();
FileOutputStream fileoutputStream = new FileOutputStream(URLtoFileWriting.destinationFile);
IOUtils.copy(inputStream, fileoutputStream);
FileInputStream FIS = new FileInputStream(URLtoFileWriting.destinationFile);
Workbook wb = WorkbookFactory.create(FIS);
FIS.close();
inputStream.close();
fileoutputStream.close();
System.out.println(URLtoFileWriting.destinationFile);
System.out.println(URLtoFileWriting.destinationFile.delete());
} catch (IOException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidFormatException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (MalformedURLException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I hope this helps.
Find the solution here Close Filehandle for Workbook (apache poi).
Use NPOIFSFileSystem#close() or OPCPackage#close().
For more info have a look at the overloaded constructors of WorkbookFactory class.

how to open .mdb from ftp location jackcess

hi all with this code i can successfully download allpg.mdb and displaying...
now i want to save the downloaded file to c:/folder....
if i edit
dbTempFile = File.createTempFile("dbTempFile",".mdb"); to
dbTempFile = File.createTempFile("c:/dbTempFile",".mdb"); than it give : The filename, directory name, or volume label syntax is incorrect error.
i just want to save the downloaded file to any where to my local drive.
here is code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Table;
public class DownloadFile {
public static void main(String[] args) throws Exception {
FTPClient client = new FTPClient();
File dbTempFile=null;
FileOutputStream fileOutputStream = null;
try {
client.connect("ftp.mypak.com");
client.login("myid", "mypwd");
client.setFileType(FTPClient.BINARY_FILE_TYPE);
dbTempFile = File.createTempFile("dbTempFile",".mdb");
fileOutputStream = new FileOutputStream(dbTempFile);
client.retrieveFile("/HASSAN/MDMSTATS/allpg.mdb", fileOutputStream);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
System.out.println("got");
Table table = Database.open(dbTempFile).getTable("items");
System.out.println(table.display());
System.out.println("got");
}
client.disconnect();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
You are not giving the right file name to the Jackcess constructor. should be:
Table table = Database.open(dbTempFile).getTable("items");

Where must i copy the default.properties file in Netbeans 7.1 for java code?

i'm trying a code found with google which allows to retrieve emails from gmail and store to mysql.
When i launch the code, it's working but at the end i have an error message:
Cannot connet to database.
It's normal because i didn't knwow how to create the default.properties file:
i know the content but in which format must be the file and where must i put this file, in Netbeans??
Do i have to create a folder?
which file format txt, java??
the name of the file will be default.properties
The code will be found here: sakthimaharai.hubpages.com
I need a hlep
please.
Thank you
In Netbeans you can create a properties file using the contextual menu to create new elements, as per this answer. Be careful of entering default as the name since NB will add the .properties to whatever you write and you might end with default.properties.properties.
The most common thing is to read properties files from the classpath or from the working directory, in the first case you should create the file in the root of the Source folder. In the second case you can create the file directly in the Project node but in this case the file won't be added to the final jar/war if you want to distribute your program.
Examples of the format (and even some code to handle properties files).
I don't know from where the code is trying to load the properties, you have not said much, but under normal conditions the file should be in the project's classpath.
A property file (.properties) looks like this:
key=value
key2=value2
#comment1
Provide more info so we can help you.
OK here is the complete code found in google and removed by the author today, so it's free here for anyone is interrested.
package inboxreader;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.HashSet;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
public class InboxReader {
static HashSet<String> mails;
public static void main(String args[])
{
while(true)
{
try {
System.out.println("Started.......");
Start();
System.out.println("...Read completed.......");
try {
Thread.sleep(1000*60*5);
} catch (InterruptedException e1) {
}
} catch (Exception e) {
try {connecttoMySql();
e.printStackTrace();
System.out.println("..Error in connection Sleeping...");
} catch (Exception e1) {
}
}
}
}
public static void Start() throws Exception {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "email#gmail.com", "password");
System.out.println(store);
int cout=0;
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_WRITE);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
mails=new HashSet<String>();
System.out.println("Reading:"+ (messages.length-cout));
cout++;
InboxReader.storeAddresses(message);
dumpPart(message);
for(String temp:mails)
System.out.println(temp);
connecttoMySql();
message.setFlag(Flags.Flag.DELETED, true);
}
} catch (NoSuchProviderException e) {
connecttoMySql();
e.printStackTrace();
} catch (MessagingException e) {
connecttoMySql();
e.printStackTrace();
}
}
public static void storeAddresses(Message msg)
{
try {
for(Address adr:msg.getAllRecipients())
{
addAddresses(adr.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void addAddresses(String input_text)
{
Pattern p= Pattern.compile("[A-Z0-9\\._%\\+\\-]+#[A-Z0-9\\.\\-]+\\.[A-Z]{2,4}",Pattern.CASE_INSENSITIVE);
Matcher m=p.matcher(input_text);
while(m.find())
{
mails.add(m.group());
}
}
public static void dumpPart(Part p) throws Exception {
if (p.isMimeType("text/plain")) {
try{
addAddresses((String)p.getContent());
}catch(Exception e){}
} else {
MimeMultipart mb = null;
try{
mb=(MimeMultipart ) (p.getContent());
}
catch(Exception e)
{ try{
if(p.getContent() instanceof String)
addAddresses((String)p.getContent());
}catch(Exception e1){}
return;
}
MimeBodyPart mb1=(MimeBodyPart) mb.getBodyPart(0);
mb1.saveFile("emailtext.html");
BufferedReader br = new BufferedReader(new FileReader("emailtext.html"));
StringBuffer content = new StringBuffer();
String line ="";
while((line = br.readLine())!= null )
{
if(line.length()>=2)if(line.substring(line.length()-1).equals("="))
{
content.append(line.substring(line.length()-1) );
}else
content.append(line+"\n");
}
addAddresses(content.toString());
}
}
public static void connecttoMySql()
{
Connection conn = null;
try
{
Properties details= new Properties();
details.load(new FileInputStream("details.properties"));
String userName = details.getProperty("root");
String password = details.getProperty("password_of-mysql");
String url = details.getProperty("jdbc:mysql://localhost/Test");
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
PreparedStatement st= conn.prepareStatement("insert into `Email_list` values(?)");
for(String mail:mails)
{
try{
st.setString(1, mail);
st.execute();
}catch(Exception e){}
}
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
e.printStackTrace();
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { }
}
}
}
}
and the error message is:
Cannot connect to database server
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:303)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:316)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at inboxreader.InboxReader.connecttoMySql(InboxReader.java:180)
at inboxreader.InboxReader.main(InboxReader.java:47)
com.sun.mail.util.DecodingException: BASE64Decoder: Error in encoded stream: needed 4 valid base64 characters but only got 2 before EOF, the 10 most recent characters were: "AKxCo9RUjD"
..Error in connection Sleeping...
And create the file default.properties.properties as explained in the example of Madth3
Thank you
And the default.properties.properties is:
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class App
{
public static void main( String[] args )
{
Properties prop = new Properties();
try {
//set the properties value
prop.setProperty("database", "localhost");
prop.setProperty("dbuser", "root");
prop.setProperty("dbpassword", "password");
//save properties to project root folder
prop.store(new FileOutputStream("default.properties.properties"), null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Categories