I'm trying to upload a text file to a server via FTP. The text file is in data/data/my package/files (I have checked in the DDMS). I am getting a filenotfoundexception in LogCat.
Here's my code:
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("82.163.99.80");
client.enterLocalPassiveMode();
client.login("user", "password");
//
// Create an InputStream of the file to be uploaded
//
String filename = "sdcardstats.txt";
fis = new FileInputStream(filename);
//
// Store file to server
//
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
Can anyone help please?
Your code:
fis = new FileInputStream(filename);
... requires a path, not a file name.
Try instead:
fis = openFileInput(filename);
... which takes a file name and tries to open it in your application's private file storage area. For more information, see the Android Developers Guide for Data Storage: Internal Files, and FileInputStream and openFileInput.
Related
I want to save some images in internal storage. Here is my code:
Bitmap bitmap = ((BitmapDrawable)iv_add.getDrawable()).getBitmap();
File file = getApplicationContext().getDir("Images",MODE_PRIVATE);
file = new File(file, "UniqueFileName"+".jpg");
try{
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e)
{
e.printStackTrace();
}
As I understood, the picture needs to go into internal_storage/android/data/project_name/file. When I choose a picture from my gallery and click the button to save it, nothing happens and the program starts lagging. What can I do?
This line is your problem.
ContextWrapper wrapper = new ContextWrapper(getApplicationContext());
You are not supposed to create the context wrapper yourself.
File file = getApplicationContext().getDir("Images",MODE_PRIVATE);
file = new File(file, "UniqueFileName"+".jpg");
try{
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e)
{
e.printStackTrace();
}
i'm attempting to fetch a list of files from server and copy them to directory .
and this error prompts.
java.rmi.NoSuchObjectException: no such object in table
at javafxhomeui_1.HomeUI_2Controller.writeFileToLocalHDD(HomeUI_2Controller.java:427)
at javafxhomeui_1.HomeUI_2Controller.initialize(HomeUI_2Controller.java:312)
HomeUI_2Controller.java
RemoteInputStream ris= null;
File[] iconlist=null;
try {
File appicon=new File("D:\\SERVER\\Server Content\\Apps\\icons");
iconlist=appicon.listFiles();
for (File file1 : iconlist) {
ris = downloadcontroller.getFile(file1.getAbsolutePath());
System.out.println(file1.getName());
}
} catch (Exception ex) {
Logger.getLogger(HomeUI_2Controller.class.getName()).log(Level.SEVERE, null, ex);
}
try {
for (File file1 : iconlist) {
//System.out.println("D:\\client\\Temp\\"+file1.getName());
/*line:312 */ writeFileToLocalHDD(ris,"D:\\client\\Temp\\"+file1.getName());
}
} catch (Exception ex) {
Logger.getLogger(HomeUI_2Controller.class.getName()).log(Level.SEVERE, null, ex);
}
public static void writeFileToLocalHDD(RemoteInputStream inFile, String fileLocation) throws IOException {
// wrap RemoteInputStream as InputStream (all compression issues are dealt
// with in the wrapper code)
/* line:427*/ InputStream istream = RemoteInputStreamClient.wrap(inFile);
BufferedInputStream bis = new BufferedInputStream(istream);
//downloaded file...
File file = new File(fileLocation);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
FileChannel channel = fileOutputStream.getChannel();
byte b[] = new byte[1024];
long startTime = System.currentTimeMillis();
while (bis.available()>0) {
bis.read(b);
System.out.println((System.currentTimeMillis() - startTime)/1000);
ByteBuffer buffer = ByteBuffer.wrap(b);
channel.write(buffer);
}
bis.close();
fileOutputStream.flush();
channel.close();
fileOutputStream.close();
}
////////////////////////////////////////////////
public RemoteInputStream getFile(String fileName) throws IOException {
// create a RemoteStreamServer (note the finally block which only releases
// the RMI resources if the method fails before returning.)
//read data
RemoteInputStreamServer istream = null;
try {
File file = new File(fileName);
System.out.println(file.exists());
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(
fileInputStream);
istream = new SimpleRemoteInputStream(bufferedInputStream);
// export the final stream for returning to the client
//send data
RemoteInputStream result = istream.export();
// after all the hard work, discard the local reference (we are passing
// responsibility to the client)
istream = null;
return result;
} finally {
// we will only close the stream here if the server fails before
// returning an exported stream
if (istream != null) {
istream.close();
}
}
}
////////////////////////////////////
rmi works on a stub and skeleton structure.
Exception that is thrown has something to do with rmi Registry. The Object is not found because it is not available from RMI resistry.
A NoSuchObjectException is thrown if an attempt is made to invoke a method on an object that no longer exists in the remote virtual machine
as in javaDoc of the Exception thrown
I'm trying to upload an image from android to ftp server, but when i try to open the image that i uploaded i see the following message instead of the image "the image cannot be displayed because it contains errors"
and this is the code that i use
public void uploadImage(String path){
String server = "www.domainname.com";
int port = 21;
String user = "ftp-username";
String pass = "ftp-password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// APPROACH #1: uploads first file using an InputStream
File firstLocalFile = new File(path);
long fileSize = firstLocalFile.length();
Log.i("File Size",fileSize+"");
String firstRemoteFile = "testfile1.jpg";
InputStream inputStream = new FileInputStream(firstLocalFile);
Log.i("uploading", "Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
if (done) {
Log.i("uploaded", "finished uploading first file");
}
// APPROACH #2: uploads second file using an OutputStream
File secondLocalFile = new File(path);
String secondRemoteFile = "testfile2.jpg";
inputStream = new FileInputStream(secondLocalFile);
Log.i("uploading", "Start uploading second file");
OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
byte[] bytesIn = new byte[4096];
int read = 0;
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
}
inputStream.close();
outputStream.close();
boolean completed = ftpClient.completePendingCommand();
if (completed) {
Log.i("uploaded", "finished uploading second file");
}
} catch (IOException ex) {
Log.i("Error", "Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
where is the error!!?
Thanks in advance..
This looks suspiciously like this bug: FTPClient corrupts the images while uploading to ftp server on android?
Try using FTP4J instead.
I am working on an applet that records voice and uploads to a servlet.
Here is the code of the upload thread in the applet
class uploadThread extends Thread {
#Override
public void run() {
try {
//Preparing the file to send
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
File file = File.createTempFile("uploded", ".wav");
byte audio[] = out.toByteArray();
InputStream input = new ByteArrayInputStream(audio);
final AudioFormat format = getFormat();
final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize());
AudioSystem.write(ais, fileType, file);
//uploading to servlet
FileInputStream in = new FileInputStream(fileToSend);
byte[] buf = new byte[1024];
int bytesread = 0;
String toservlet = "http://localhost:8080/Servlet/upload";
URL servleturl = new URL(toservlet);
URLConnection servletconnection = servleturl.openConnection();
servletconnection.setDoInput(true);
servletconnection.setDoOutput(true);
servletconnection.setUseCaches(false);
servletconnection.setDefaultUseCaches(false);
DataOutputStream out = new DataOutputStream(servletconnection.getOutputStream());
while ((bytesread = in.read(buf)) > -1) {
out.write(buf, 0, bytesread);
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error during upload");
}
}
}//End of inner class uploadThread
Here is the code of the grab file method in the servlet:
java.io.DataInputStream dis = null;
try {
int fileLength = Integer.valueOf(request.getParameter("fileLength"));
String fileName = request.getParameter("fileName");
dis = new java.io.DataInputStream(request.getInputStream());
byte[] buffer = new byte[fileLength];
dis.readFully(buffer);
dis.close();
File cibleServeur = new File("/Users/nebrass/Desktop/" + fileName);
FileOutputStream fos = new FileOutputStream(cibleServeur);
fos.write(buffer);
fos.close();
} catch (IOException ex) {
Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
dis.close();
} catch (Exception ex) {
Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
I have created a certificate with the keytool. And i have signed the JAR of the applet.
I have added the applet to the jsp file and it is working, and have the all permissions (I tried to save a file on a desktop using the applet)
Update: The problem is that the file is not sent, and when i try to debug the servlet, it is not invoked by the the applet.
Please help
That's not how it works. You've just opened a URLConnection and wrote to the output stream. That way you're assuming something like a socket connection, but here we need more of a HttpUrlConnection and then a request-parameter and a multi-part request.
Google Search
Google found lots of solutions, but for the completeness of the answer, I'm adding one below :
https://stackoverflow.com/a/11826317/566092
You want up upload a file from the server to the user desktop?
I doubt this will be allowed, for obvious security reasons.
Why don't you just call the servlet directly from the browser? And "save as" the file?
Here is an exemple on how to send a file (any type) from a servlet.
protected void doPost(
...
response.setContentType("your type "); // example: image/jpeg, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/octet-stream
response.setHeader("Content-Disposition","attachment; filename=\"your_filename\"");
File uploadedFile = new File("/your_file_folde/your_file_name");
if (uploadedFile.exists()){
FileUtils.copyFile(uploadedFile, response.getOutputStream());
}
else { // Error message
}
....
}
I created a function to download files from an FTP server that I have access to. How would I upload files back to the FTP server?
Below is the download_files method i used:
public static void download_files(String un, String pw, String ip, String dir, String fn, String fp){
URLConnection con;
BufferedInputStream in = null;
FileOutputStream out = null;
try{
URL url = new URL("ftp://"+un+":"+pw+"#"+ip+"/"+dir+"/"+fn+";type=i");
con = url.openConnection();
in = new BufferedInputStream(con.getInputStream());
out = new FileOutputStream(fp+fn);
int i = 0;
byte[] bytesIn = new byte[1024];
while ((i = in.read(bytesIn)) >= 0) {
out.write(bytesIn, 0, i);
}
}catch(Exception e){
System.out.print(e);
e.printStackTrace();
System.out.println("Error while FTP'ing "+fn);
}finally{
try{
out.close();
in.close();
}catch(IOException e){
e.printStackTrace();
System.out.println("Error while closing FTP connection");
}
}
}
Use the FTPClient Class from the Apache Commons Net library.
This is a snippet with an example:
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("ftp.domain.com");
client.login("admin", "secret");
//
// Create an InputStream of the file to be uploaded
//
String filename = "Touch.dat";
fis = new FileInputStream(filename);
//
// Store file to server
//
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
Snippet taken from http://www.kodejava.org/examples/356.html
I have used the EDT FTP package, a free GPL library for FTP in Java: http://www.enterprisedt.com/products/edtftpj/overview.html
Here is a code sample, from the Demo.java class they provide:
ftp = new FTPClient();
ftp.setRemoteHost("hostname");
// connect
ftp.connect();
// login
ftp.login("user", "password");
// set up passive ASCII transfers
ftp.setConnectMode(FTPConnectMode.PASV);
ftp.setType(FTPTransferType.ASCII);
// get directory and print it to console
String[] files = ftp.dir(".", true);
for (int i = 0; i < files.length; i++)
log.debug(files[i]);
// copy file to server
ftp.put("test.txt", "test.txt");
// copy file from server
ftp.get("test.txt" + ".copy", "test.txt");
// delete file from server
ftp.delete("test.txt");
// Shut down client
ftp.quit();
Check out FTP4J as well...
Take a look at apache-commons-net they have a some FTP tools which may help you out!