0 byte file getting created in ftp location - java

Following is my java function to write a csv file in ftp location.The file gets created to ftp location but the file size is 0 bytes and file is empty.Kindly help as I am stuck
public int WriteFileToFtp(String FileName, String FileData) {
//get these details for the version??
//??
FTPClient ftp= new FTPClient();
try {
InputStream is = new ByteArrayInputStream(FileData.getBytes("ISO-8859-1"));
ftp.connect(ftpIP);
boolean isConnection = ftp.login(userName,password);
if(!isConnection){
logger.error("Connection failed");
return -1;
}
ftp.enterLocalActiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);//setting fileType
//?? go to directory using the circle code
if(ftpDirectoryToBeUpdate!=null && ftpDirectoryToBeUpdate.trim().length()>0)
{
logger.error("Changing directory for write="+ftpDirectoryToBeUpdate+" lcd="+ftp.printWorkingDirectory());
ftp.changeWorkingDirectory(ftpDirectoryToBeUpdate);
logger.error("Changed directory for write="+ftpDirectoryToBeUpdate+" lcd="+ftp.printWorkingDirectory());
}else
{
logger.error("Changed directory for write failed lcd="+ftp.printWorkingDirectory());
logger.error("DirectoryToReadFrom="+ftpDirectoryToBeUpdate);
}
ftp.storeFile(FileName,is) ;
logger.error(ftp.getReplyString());
is.close();
if(ftp.isConnected())
ftp.disconnect();
} catch (SocketException e) {
//logger.error(LoggerKeyWord.ERROR_ALERT + " FTP WRITE ERROR");
logger.error(e,e);
e.printStackTrace();
return -1;
} catch (IOException e) {
// logger.error(LoggerKeyWord.ERROR_ALERT + " FTP WRITE ERROR");
logger.error(e,e);
e.printStackTrace();
return -1;
}
try {
if(ftp.isConnected())
ftp.disconnect();
} catch (IOException e) {
logger.error (e,e);
e.printStackTrace();
return -1;
}
return 1;
}

have you tried closing input stream before saving the file?

Related

Error when connecting to FTP using apache commons

I am using apache common library for connecting to FTP with Android app.
Now I want to upload a file from internal storage to FTP server and I get this reply from getReplyString() method.
And I get this msg
553 Can't open that file: Permission denied
//Write file to the internal storage
String path = "/sdcard/";
File file = new File(path, fileName);
FileOutputStream stream = null;
try {
stream = new FileOutputStream(file);
stream.write(jsonObject.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Read the file from resources folder.
try {
File file1 = new File(path, fileName);
Log.d("path",file1.getPath());
BufferedInputStream in = new BufferedInputStream (new FileInputStream (file1.getPath()));
client.connect(FTPHost);
client.login(FTPUserName, FTPPassword);
client.enterLocalPassiveMode();
client.setFileType(FTP.BINARY_FILE_TYPE);
// Store file to server
Log.d("reply",client.getReplyString());
boolean res = client.storeFile("/"+fileName, in);
Log.d("reply",client.getReplyString());
Log.d("result",res+"");
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}

Why is my .bin file being overwritten when I read data from it? (Java)

I made my own data structure called a User. I am trying to store Users in a .bin file using FileInputStream and FileOutputStream. I am successfully storing a single user when a button is pressed, but then when I close the application and go to read my Users and recognize login info, the .bin file turns blank.
I know that the .bin file is not empty after the program closes, but then when I try to read the file I get a EOFException. Here is my code to read objects from the file:
public void loadUsers() {
try {
ObjectInputStream ois = new ObjectInputStream(fi);
boolean endOfFile = false;
while (!endOfFile) {
try {
System.out.println("loaded a user!");
User person = (User) ois.readObject();
Users.addUser(person);
} catch (EOFException e) {
endOfFile = true;
ois.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Here is my code to write objects to the file:
public void storeUser(User person) {
boolean endOfFile = false;
try {
new ObjectInputStream(fi).readObject();
} catch (EOFException e) {
endOfFile = true;
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
if (!endOfFile) {
System.out.println("Appending!");
try {
AppendingObjectOutputStream aos = new AppendingObjectOutputStream(fo);
aos.writeObject(person);
aos.flush();
aos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Writing a new file!");
try {
ObjectOutputStream oos = new ObjectOutputStream(fo);
oos.writeObject(person);
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AppendingObjectOutputStream is just a small subclass of ObjectOutputStream I made that overwrites writeStreamHeader() so that there is no header placed in my file when try to write more users. I don't think this is related to the problem because I have yet to write a User onto a file with Users already written on it.

FTP file successfully transferred but is not true

Here is my simple code:
public boolean sendCSV() throws IOException {
System.out.println("Translating from xls to csv...");
File xls = new File("file.xls");
File csvFile;
csvFile = CSVManager.xlsToCsv(xls);
csvFile.renameTo(new File("file.csv"));
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
System.out.println("Establishing connection...");
client.connect(ftpHost, ftpPort);
System.out.print(client.getReplyString());
System.out.println("Connection ok.");
if (client.login(ftpUser, ftpPass)) {
System.out.println("Login ok");
System.out.print(client.getReplyString());
System.out.println("Setting PASV");
client.enterLocalPassiveMode();
System.out.print(client.getReplyString());
if (client.changeWorkingDirectory("/MYDIR")) {
System.out.println("Dir changed");
System.out.print(client.getReplyString());
} else {
System.out.println("Error changing dir");
System.out.print(client.getReplyString());
}
String filename = csvFile.getName();
TrayIconManager.SwitchTrayToFull();
fis = new FileInputStream(filename);
if (client.storeFile(filename, fis)) {
System.out.println("File sent");
System.out.print(client.getReplyString());
} else {
System.out.println("Error during sending file");
System.out.print(client.getReplyString());
}
}
if (client.logout()) {
System.out.println("Logout ok");
System.out.print(client.getReplyString());
return true;
} else {
System.out.println("Logout problem");
System.out.print(client.getReplyString());
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
What is the problem? The output says that
File sent
226-29 Kbytes used (0%) - authorized: 512000 Kb
226-File successfully transferred
226 0.343 seconds (measured here), 30.59 Kbytes per second
but is not true, because once I check on the ftp server the file is not there!
Why Kbytes used is 0%? Maybe is that the error?
The code seems to be ok, also the output.
So what is the real problem?

how can i transfer multiple files in a directory from client to server through java socket? [duplicate]

This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
I have created a simple client-server java socket app that can transfer a single file from client into the server through socket. What do I need to modify in my application so that I can send multiple files in a directory to the server?
this my simple client:
public void connect() {
while (!isConnected) {
try {
socket = new Socket("10.110.190.82", 7999);
outputStream = new ObjectOutputStream(socket.getOutputStream());
isConnected = true;
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error. Server is not running\n '"+e.getMessage()+"' "+
"\nThis Client will now close.", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
}
public void sendFile(String sourceFilePath, String fileName) {
if(socket.isConnected()){
while (socket.isConnected()) {
fileEvent = new FileEvent_1();
String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1);
fileEvent.setDestinationDirectory(destinationPath);
fileEvent.setFilename(fileName);
fileEvent.setSourceDirectory(sourceFilePath);
File file = new File(sourceFilePath);
if (file.isFile()) {
try {
DataInputStream diStream = new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read,
fileBytes.length - read)) >= 0) {
read = read + numRead;
}
fileEvent.setFileSize(len);
fileEvent.setFileData(fileBytes);
fileEvent.setStatus("Success");
} catch (Exception e) {
e.printStackTrace();
fileEvent.setStatus("Error");
}
} else {
System.out.println("path specified is not pointing to a file");
fileEvent.setStatus("Error");
}
try {
outputStream.writeObject(fileEvent);
System.out.println("Done...Going to exit");
JOptionPane.showMessageDialog(null, "Upload Success", "Success", JOptionPane.INFORMATION_MESSAGE);
Thread.sleep(3000);
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
} catch(InterruptedException ex){
ex.printStackTrace();
}
}
} else {
JOptionPane.showMessageDialog(null, "Socket is not connected", "FAILED", JOptionPane.ERROR_MESSAGE);
}
}
and this is my simple server, it contains a client handler and a server..
this is client_handler:
public class ClientHandler implements Runnable {
Socket socket;
PrintStream out;
private ObjectInputStream inputStream;
private FileEvent_1 fileEvent;
private File dstFile;
private FileOutputStream fileOutputStream;
ClientHandler(Socket s) {
socket = s;
}
#Override
public void run() {
try {
out = new PrintStream(socket.getOutputStream());
inputStream = new ObjectInputStream(socket.getInputStream());
downloadFile();
} catch (IOException e) {
System.out.println("PrintStream Error");
}
out.println("Hello!! I'm in!!!");
try {
socket.close();
} catch (IOException e) {
System.out.println("Failed to close, oddly...");
}
}
public void downloadFile() {
try {
fileEvent = (FileEvent_1) inputStream.readObject();
if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
System.out.println("Error occurred ..So exiting");
System.exit(0);
}
String outputFile = fileEvent.getDestinationDirectory() + fileEvent.getFilename();
if (!new File(fileEvent.getDestinationDirectory()).exists()) {
new File(fileEvent.getDestinationDirectory()).mkdirs();
}
dstFile = new File(outputFile);
fileOutputStream = new FileOutputStream(dstFile);
fileOutputStream.write(fileEvent.getFileData());
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("Output file : " + outputFile + " is successfully saved ");
Thread.sleep(000);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}}
and the server:
public static void main(String[] args) {
try {
socket = new ServerSocket(port);
System.out.println("SERVER START");
System.out.println("Bound to port: " + port);
} catch (IOException e) {
System.out.println("Cannot bind to port: " + port);
System.exit(0);
}
while (true) {
try {
Socket s = socket.accept();
System.out.println("New Client: "+s.getInetAddress().toString());
(new Thread(new ClientHandler(s))).start();
} catch (IOException e) {
System.out.println("Failed to accept client");
}
}
}
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
So you get the directory listing (list of all files in the directory), loop through the resulting fList and send them one by one as you would with a single file:
for(File file : fList) {
//file sending stuff
}
You can use JFileChooser if you want see the list of directories and list of files. for example:
JFileChooser jFilechooser1= new JFileChooser(new File("."));
to select the file:
if (jFilechooser1.showOpenDialog(this)==JFileChooser.APPROVE_OPTION)
{
dstFile=jFilechooser1.getSelectedFile();
}

How to overwrite a file if it already exists in dropbox?

I am uploading a file in dropbox by this method:
public void upload() {
FileInputStream inputStream = null;
try {
File file = new File(Environment.getExternalStorageDirectory()
.toString() + "/write.txt");
inputStream = new FileInputStream(file);
Entry newEntry = mDBApi.putFile("/write.txt", inputStream,
file.length(), null, null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + newEntry.rev);
} catch (DropboxUnlinkedException e) {
// User has unlinked, ask them to link again here.
Log.e("DbExampleLog", "User has unlinked.");
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
but when already this file exists in the folder then the file get renamed to write(1).txt
but I want that if the file already exists in the dropbox share folder then it will be replaced. What should I do now?
You can use mDBApi.putFileOverwrite instead of mDBApi.putFile

Categories

Resources