Unzip files in FTP server using Java - java

I am trying to unzip files in the FTP location, but when i unzip i am not able to get all the files in FTP server, but when i try the code to unzip files to local machine it is working. I am sure somewhere while writing the data to FTP i am missing something.Below is my code. Please help me on this.
public void unzipFile(String inputFilePath, String outputFilePath) throws SocketException, IOException {
FileInputStream fis = null;
ZipInputStream zipIs = null;
ZipEntry zEntry = null;
InputStream in = null;
FTPClient ftpClientinput = new FTPClient();
FTPClient ftpClientoutput = new FTPClient();
String ftpUrl = "ftp://%s:%s#%s/%s;type=i";
ftpClientinput.connect(server, port);
ftpClientinput.login(user, pass);
ftpClientinput.enterLocalPassiveMode();
ftpClientinput.setFileType(FTP.BINARY_FILE_TYPE);
String uploadPath = "path";
ftpClientoutput.connect(server, port);
ftpClientoutput.login(user, pass);
ftpClientoutput.enterLocalPassiveMode();
ftpClientoutput.setFileType(FTP.BINARY_FILE_TYPE);
try {
// fis = new FileInputStream(inputFilePath);
String inputFile = "/Srikanth/RecordatiFRA_expenses.zip";
String outputFile = "/Srikanth/FR/";
in = ftpClientinput.retrieveFileStream(inputFile);
zipIs = new ZipInputStream(new BufferedInputStream(in));
while ((zEntry = zipIs.getNextEntry()) != null) {
try {
byte[] buffer = new byte[4 * 8192];
FileOutputStream fos = null;
OutputStream out = null;
// String opFilePath = outputFilePath + zEntry.getName();
String FTPFilePath = outputFile + zEntry.getName();
// System.out.println("Extracting file to "+opFilePath);
System.out.println("Extracting file to " + FTPFilePath);
// fos = new FileOutputStream(opFilePath);
out = ftpClientoutput.storeFileStream(FTPFilePath);
// System.out.println(out);
int size;
while ((size = zipIs.read(buffer, 0, buffer.length)) != -1) {
// fos.write(buffer, 0 , size);
out.write(buffer, 0, size);
}
// fos.flush();
// fos.close();
} catch (Exception ex) {
ex.getMessage();
}
}
zipIs.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (ftpClientinput.isConnected()) {
ftpClientinput.logout();
ftpClientinput.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Related

How can I run executable in assets?

How can I add a executable into assets and run it in Android and show the output?
I've a executable that will work. I assume there will need to be some chmod in the code.
Thank you.
here is my answer
put copyAssets() to your mainactivity.
someone's code:
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getFilesDir(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
also here is code to run command
public String runcmd(String cmd){
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer out = new StringBuffer();
while ((read = in.read(buffer)) > 0) {
out.append(buffer, 0, read);
}
in.close();
p.waitFor();
return out.substring(0);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
you may need to change it to
String prog= "programname";
String[] env= { "parameter 1","p2"};
File dir= new File(getFilesDir().getAbsolutePath());
Process p = Runtime.getRuntime().exec(prog,env,dir);
to ensure proper parameter handling
also add this to your main code
to check proper copying of files
String s;
File file4 = new File(getFilesDir().getAbsolutePath()+"/executable");
file4.setExecutable(true);
s+=file4.getName();
s+=file4.exists();
s+=file4.canExecute();
s+=file4.length();
//output s however you want it
should write: filename, true, true, correct filelength.
Place your executable in raw folder, then run it by using ProcessBuilder or Runtime.exec like they do here http://gimite.net/en/index.php?Run%20native%20executable%20in%20Android%20App

Moving DB to SDCard [duplicate]

I'm using the code below to try and move my database file to my sdcard. I have no problems except that I get a redline under sd. Any ideas?
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "\\data\\application.package\\databases\\name";
String backupDBPath = "name";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src;
try {
src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
try {
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
You can only use a variable if you create an instance of it:
Put this before your code:
File sd = Environment.getExternalStorageDirectory();
if you are using SQLite database try this:
public class _DBHelper extends SQLiteOpenHelper {
public boolean backUp() throws Exception
{
InputStream input = null;
OutputStream output = null;
try {
SQLiteDatabase db = this.getReadableDatabase();
String strSource = db.getPath();
String strDest = Utilities.getAppDocumentsFolder(_context) + "/"
+ DATABASE_NAME;
File fileDest = new File(strDest);
if (fileDest.exists())
{
fileDest.delete();
}
input = new FileInputStream(strSource);
output = new FileOutputStream(strDest);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} catch (Exception e) {
throw e;
} finally
{
if (output != null)
{
output.flush();
output.close();
}
if (input != null)
{
input.close();
}
}
return true;
}
}

Moving my db to sd card not working

I'm using the code below to try and move my database file to my sdcard. I have no problems except that I get a redline under sd. Any ideas?
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "\\data\\application.package\\databases\\name";
String backupDBPath = "name";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src;
try {
src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
try {
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
You can only use a variable if you create an instance of it:
Put this before your code:
File sd = Environment.getExternalStorageDirectory();
if you are using SQLite database try this:
public class _DBHelper extends SQLiteOpenHelper {
public boolean backUp() throws Exception
{
InputStream input = null;
OutputStream output = null;
try {
SQLiteDatabase db = this.getReadableDatabase();
String strSource = db.getPath();
String strDest = Utilities.getAppDocumentsFolder(_context) + "/"
+ DATABASE_NAME;
File fileDest = new File(strDest);
if (fileDest.exists())
{
fileDest.delete();
}
input = new FileInputStream(strSource);
output = new FileOutputStream(strDest);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} catch (Exception e) {
throw e;
} finally
{
if (output != null)
{
output.flush();
output.close();
}
if (input != null)
{
input.close();
}
}
return true;
}
}

How to download a text file via FTP and read the contents to a string

This is re-worded from a previous question (which was probably a bit unclear).
I want to download a text file via FTP from a remote server, read the contents of the text file into a string and then discard the file. I don't need to actually save the file.
I am using the Apache Commons library so I have:
import org.apache.commons.net.ftp.FTPClient;
Can anyone help please, without simply redirecting me to a page with lots of possible answers on?
Not going to do the work for you, but once you have your connection established, you can call retrieveFile and pass it an OutputStream. You can google around and find the rest...
FTPClient ftp = new FTPClient();
...
ByteArrayOutputStream myVar = new ByteArrayOutputStream();
ftp.retrieveFile("remoteFileName.txt", myVar);
ByteArrayOutputStream
retrieveFile
Normally I'd leave a comment asking 'What have you tried?'. But now I'm feeling more generous :-)
Here you go:
private void ftpDownload() {
FTPClient ftp = null;
try {
ftp = new FTPClient();
ftp.connect(mServer);
try {
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
throw new Exception("Connect failed: " + ftp.getReplyString());
}
if (!ftp.login(mUser, mPassword)) {
throw new Exception("Login failed: " + ftp.getReplyString());
}
try {
ftp.enterLocalPassiveMode();
if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
Log.e(TAG, "Setting binary file type failed.");
}
transferFile(ftp);
} catch(Exception e) {
handleThrowable(e);
} finally {
if (!ftp.logout()) {
Log.e(TAG, "Logout failed.");
}
}
} catch(Exception e) {
handleThrowable(e);
} finally {
ftp.disconnect();
}
} catch(Exception e) {
handleThrowable(e);
}
}
private void transferFile(FTPClient ftp) throws Exception {
long fileSize = getFileSize(ftp, mFilePath);
InputStream is = retrieveFileStream(ftp, mFilePath);
downloadFile(is, buffer, fileSize);
is.close();
if (!ftp.completePendingCommand()) {
throw new Exception("Pending command failed: " + ftp.getReplyString());
}
}
private InputStream retrieveFileStream(FTPClient ftp, String filePath)
throws Exception {
InputStream is = ftp.retrieveFileStream(filePath);
int reply = ftp.getReplyCode();
if (is == null
|| (!FTPReply.isPositivePreliminary(reply)
&& !FTPReply.isPositiveCompletion(reply))) {
throw new Exception(ftp.getReplyString());
}
return is;
}
private byte[] downloadFile(InputStream is, long fileSize)
throws Exception {
byte[] buffer = new byte[fileSize];
if (is.read(buffer, 0, buffer.length)) == -1) {
return null;
}
return buffer; // <-- Here is your file's contents !!!
}
private long getFileSize(FTPClient ftp, String filePath) throws Exception {
long fileSize = 0;
FTPFile[] files = ftp.listFiles(filePath);
if (files.length == 1 && files[0].isFile()) {
fileSize = files[0].getSize();
}
Log.i(TAG, "File size = " + fileSize);
return fileSize;
}
You can just skip the download to local filesystem part and do:
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
InputStream inputStream = ftpClient.retrieveFileStream("/folder/file.dat");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "Cp1252"));
while(reader.ready()) {
System.out.println(reader.readLine()); // Or whatever
}
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

how to read/write text file in j2me

i want to know how to read and write text to a .txt file in j2me help me thanks...
public String readFile(String path)
{
InputStream is = null;
FileConnection fc = null;
String str = "";
try
{
fc = (FileConnection)Connector.open(path, Connector.READ_WRITE);
if(fc.exists())
{
int size = (int)fc.fileSize();
is= fc.openInputStream();
byte bytes[] = new byte[size];
is.read(bytes, 0, size);
str = new String(bytes, 0, size);
}
}
catch (IOException ioe)
{
Alert error = new Alert("Error", ioe.getMessage(), null, AlertType.INFO);
error.setTimeout(1212313123);
Display.getDisplay(main).setCurrent(error);}
finally
{
try
{
if (null != is)
is.close();
if (null != fc)
fc.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
return str;
}
void writeTextFile(String fName, String text)
{
OutputStream os = null;
FileConnection fconn = null;
try
{
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
if (!fconn.exists())
fconn.create();
os = fconn.openDataOutputStream();
os.write(text.getBytes());
fconn.setHidden(false);
// fconn.setReadable(true);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
if (null != os)
os.close();
if (null != fconn)
fconn.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}

Categories

Resources