how to open .mdb from ftp location jackcess - java

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");

Related

Why doesn't FileChannel append to end of file?

I am trying to download a few different files from a REST API using Java.
So far, I am getting the files, but the content won't append to the end of an output file.
I changed the FileOutputStream constructor from new FileOutputStream(path) to new FileOutputStream(path, true) but somehow it does not work.
Can somebody please provide pointers to what I am missing?
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class GetXML {
// This Method Is Used To Download A Sample File From The Url
private static void downloadFileFromUrlUsingNio() {
String filePath ="config/sample.txt";
Scanner in = new Scanner(System.in);
System.out.println("Enter the NO which you want to parse: ");
while(in.hasNextLine()){
String sampleUrl = "e.g.comSearch?NO=" + in.nextLine();
URL urlObj = null;
ReadableByteChannel rbcObj = null;
FileOutputStream fOutStream = null;
// Checking If The File Exists At The Specified Location Or Not
Path filePathObj = Paths.get(filePath);
boolean fileExists = Files.exists(filePathObj);
if(fileExists) {
try {
urlObj = new URL(sampleUrl);
rbcObj = Channels.newChannel(urlObj.openStream());
fOutStream = new FileOutputStream(filePath, true);
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
System.out.println("! File Successfully Downloaded From The Url !");
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Downloading The File= " + ioExObj.getMessage());
} finally {
try {
if(fOutStream != null){
fOutStream.close();
System.out.println("fOutStream closed");
}
if(rbcObj != null) {
rbcObj.close();
System.out.println("rbcObj closed");
}
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
}
}
} else {
System.out.println("File Not Present! Please Check!");
}
}
in.close();
System.out.println("Scanner Closed");
}
public static void main(String[] args) {
downloadFileFromUrlUsingNio();
}
}
You have written:
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
The second parameter, 0, specifies that data should be transferred to the file at position zero. The position is absolute, and it doesn't matter that you opened the file for append, because you are ignoring the current channel position.
Note the documentation that states,
position - The position within the file at which the transfer is to begin; must be non-negative
Your code is an unconventional approach to a common task. As such, it's hard for readers to comprehend, and, when you encounter mistakes, hard for you to get help. Since URL only offers InputStream support, stick with streams, and avoid channels.

No class error for retrieving a file from FTP with Java

I am trying to make a java program that will get a csv file from FTP and update the database with it . So i started first with retrieving the file but I get the No Class Def Found Error on the FTPClient. Thats my code below .(i have imported the commons-net-3.6.jar and i use jdk-13.0.2 and i use Eclipse if that makes any difference)
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class main {
public static void main(String[] args) {
String server = "serverip";
int port = 21;
String user = "user";
String pass = "pass";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
String remoteFile1 = "filename.csv";
File downloadFile1 = new File("C:/filename.csv");
OutputStream outputStream1 = new BufferedOutputStream(new
FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
if (success) {
System.out.println("File #1 has been downloaded successfully.");
}
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Stacktrace:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/net/ftp/FTPClient
at main.main(main.java:18)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.net.ftp.FTPClient
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 1 more

Generating an xls file from an xml file

I am using the below command to convert an xml file to an excel file, but I could not generate the xls file, please advise how to do that?
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.poi.hssf.model.Workbook;
//import nl.fountain.xelem.excel.Workbook;
import nl.fountain.xelem.lex.ExcelReader;
import org.xml.sax.SAXException;
public class XmlToXls11 {
public void XML() throws ParserConfigurationException, SAXException, IOException
{
ExcelReader reader = new ExcelReader();
Workbook xlWorkbook = (Workbook) reader.getWorkbook("c:/book.xml");
}
}
have you tried the XSerializer?
public void writeExcelXmlFile(String fileNameIn, String fileNameOut){
XLDocument xldoc = new XLDocument(fileNameIn);
OutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream(fileNameOut));
new XSerializer().serialize(xldoc.getDocument(), out);
out.close();
} catch (XelemException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I guess that it's not possible to write the old xls-binary format with this library.
have a look here:
https://stackoverflow.com/questions/18177870/how-can-i-read-or-write-xls-files-using-java

Method for FileUpload throwing errors in Java-Windows

I want to test one sample program for file Uploading.But it is showing error "FileNotFoundException".
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestUpload {
/**
* #param args
*/
public boolean handleFileUpload(){
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
boolean isFileUplodedCorrectly = true;
try {
bos = new BufferedOutputStream(new FileOutputStream(new File("D:\\vishu.jpeg")));
bis = new BufferedInputStream(new FileInputStream(new File("D:\\vishuGreetings.jpeg")));
byte[] b = new byte[1024];
while (bis.read(b) != -1)
bos.write(b);
bos.flush();
} catch (Exception e) {
isFileUplodedCorrectly = false;
e.printStackTrace();
System.out.print("Exception in FileUpload Utils " + e);
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return isFileUplodedCorrectly;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestUpload tu=new TestUpload();
System.out.println("Status"+tu.handleFileUpload());
}
}
Actually the file is present there. Please Check.
java.io.FileNotFoundException: D:\vishuGreetings.jpeg (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at TestUpload.handleFileUpload(TestUpload.java:23)
at TestUpload.main(TestUpload.java:52)
Exception in FileUpload Utils java.io.FileNotFoundException: D:\vishuGreetings.jpeg (The system cannot find the file specified)Statusfalse
The file D:/vishuGreetings.jpeg is present there.But I am getting a File Not Found Exception for the same.Please check the code provided and revert back.
I solved the problem by giving .jpg instead of jpeg and found it working fine.When I check the properties of the file it is jpeg. that is why I used the extension jpeg in the file nmae in the code.Sorry for the trouble.

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