I'm trying to save image in FTP server. But it giving error like java.io.IOException: FTP error: 553 Could not create file.
I call the method
upload("xxx.xx.2.36","ftpuser","xxxxxpos",imageFile,"ftp://ftpuser#xxx.xx.2.36/Item/");
public static void check(FTPClient ftp, String cmd, boolean succeeded) throws IOException {
if (!succeeded) {
throw new IOException("FTP error: " + ftp.getReplyString());
}
}
/**
*
* #return
*/
private static String today() {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}
public static void upload(String server, String username, String Password,
File imageFile, String destDir) {
FTPClient ftp = new FTPClient();
try {
ftp.connect(server);
check(ftp, "login", ftp.login(username, Password));
System.out.println("Connected to " + server + ".");
InputStream input = new FileInputStream(imageFile);
try {
String destination = destDir;
if (destination.endsWith("/")) {
destination += today()+"-"+imageFile.getName();
System.out.println("direc" +destination);
}
check(ftp, "store", ftp.storeFile(destination, input));
System.out.println("Stored " + imageFile + " to " + destination + ".");
} finally {
input.close();
}
check(ftp, "logout", ftp.logout());
}catch(Exception e){
e.printStackTrace();
}
finally {
try {
ftp.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
After ftp.storeFile(destination, input) it giving error
Please help to solve this.
Related
I have this code:
public void uploadToFTP(File file) {
try {
final ByteArrayInputStream stream = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
String date = dateFormat.format(new Date());
String filename = date.replaceAll(":", "-");
sessionFactory.getSession().write(stream, "dir/" + filename + ".txt");
} catch (IOException e) {
e.printStackTrace();
}
}
The parameter I got in this case File I want to upload to some FTP, but the problem each time I do this the file actually is empty. When I try for example final ByteArrayInputStream stream = new ByteArrayInputStream("Text here".getBytes()); it is working fine, and stores the information inside the file, what could be the problem here, may I have problem maybe with converting the File to bytes or ?
Use thsi code :
public List<ProcessedFile> uploadFTPFilesByCridational(List<ProcessedFile> processedFiles, String sourceDir,
String destinationPath, String hostName, String userName, String password, String portNo, String extation,
int fileHours, int fileMint) {
List<ProcessedFile> processedFilesList = new ArrayList<>();
try {
FTPClient ftpClient = new FTPClient();
// client FTP connection
ftpClient = connectToFTPClient(hostName, userName, password, portNo);
// check if FTP client is connected or not
if (ftpClient.isConnected()) {
if (processedFiles != null && processedFiles.size() > 0) {
for (ProcessedFile processedFile : processedFiles) {
FileInputStream inputStream = null;
try {
File file = new File(sourceDir + "/" + processedFile.getOriginalFileName());
inputStream = new FileInputStream(file);
if (!ftpClient.isConnected()) {
ftpClient = connectToFTPClient(hostName, userName, password, portNo);
}
ByteArrayInputStream in = null;
try {
ftpClient.changeWorkingDirectory(destinationPath);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
in = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
ftpClient.storeFile(file.getName(), in);
} catch (Exception e) {
logger.error(e.getMessage());
}
inputStream.close();
in.close();
processedFile.setProcessedStatus(ProcessedStatus.COMPLETED);
processedFilesList.add(processedFile);
} catch (Exception e) {
logger.error(e);
processedFile.setProcessedStatus(ProcessedStatus.FAILED);
processedFilesList.add(processedFile);
}
}
}
}
if (ftpClient.isConnected()) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
logger.error(e.getMessage());
} finally {
try {
ftpClient.disconnect();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
}
} catch (Exception e) {
logger.error("FTP not connected exception: " + e);
}
return processedFilesList;
}
This is an assignment for a course we are having and i need some help.
I am having problems for example, trying to request a file that does not exist, it works that a 404 file not found page comes up, but when i look in the web tool for Safari i can see that the response code is 200, OK, which is definialty wrong, it should be the code that is the error.
But why i don't see, i send the error code header when a error occurs, but it´still doesn't work. Can somebody point me at the right direction or maybe just say what the problem is and i can fix it :D ?
Main:
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
public class WebServer {
private static int PORT = 8888;
private static String ROOT_DIR = "";
public static void main(String[] args) {
if (isCorrect(args) == true) {
boolean isRunning = true;
try {
/* Creates a new server socket */
ServerSocket serverSocket = new ServerSocket();
/* Binds the port to the server */
SocketAddress localBindPoint = new InetSocketAddress(PORT);
serverSocket.bind(localBindPoint);
System.out.println("==============================================" +
"\n| HTTP Web Server |" +
"\n===================" +
"\n| Configuration: " +
"\n| Directory: " +
"\n| " + ROOT_DIR +
"\n| Port: " +
"\n| " + PORT +
"\n| Usage: <directory> <port>" +
"\n| ctrl-c to exit" +
"\n==============================================");
/* The server is running */
while (isRunning) {
try {
/* Accept connection by client */
Socket socket = serverSocket.accept();
/* Each connected client gets a new thread */
new Thread(new RequestHandler(socket, ROOT_DIR)).start();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
} catch (IOException e) {
System.err.println("Address already in use!" +
"\nClose running connection or choose other port");
}
} else
usageMsg();
System.exit(1);
}
public static boolean isDirectory(String path){
File filePath = null;
try{
filePath = new File(path);
/* False if file is not a directory */
if (!filePath.isDirectory())
return false;
}
catch (Exception e){
System.err.println(e.getMessage());
}
/* Seems to be a file path */
return true;
}
public static boolean isCorrect(String[] args){
if (args.length != 2){
usageMsg();
return false;
}
try{
ROOT_DIR = args[0].toString();
PORT = Integer.parseInt(args[1]);
}
catch (NumberFormatException n){
System.err.println(n.getMessage());
}
if (!isDirectory(ROOT_DIR)){
usageMsg();
return false;
}
return true;
}
public static void usageMsg(){
System.err.println("Invalid arguments"+
"\nUsage: java -jar Webserver.jar <directory> <port>");
}
}
RequestHandler:
import java.io.*;
import java.net.Socket;
import java.util.StringTokenizer;
/**
* Web Server Request Handler.
* Created on 2015-02-16.
*/
public class RequestHandler implements Runnable {
/*
TODO ( ) Problem 1
TODO ( ) Problem 2
TODO ( ) Problem 3
TODO (X) Index page for first page.
TODO (X) Read and download images & other files
TODO ( ) Fix header responses
TODO ( ) Error responses
*/
private String
OK = "HTTP/1.0 200 OK",
NOT_FOUND = "HTTP/1.0 404 Not Found",
BAD_REQUEST = "HTTP/1.0 400 Bad Request",
FORBIDDEN = "HTTP/1.0 403 Forbidden",
SERVER_ERROR = "HTTP/1.0 500 Internal Server Error";
private String ROOT_DIR;
private Socket client;
private PrintStream send;
private DataInputStream fromClient;
private DataOutputStream out;
RequestHandler(Socket client, String ROOT_DIR) {
this.client = client;
this.ROOT_DIR = ROOT_DIR;
try {
send = new PrintStream(client.getOutputStream());
fromClient = new DataInputStream(client.getInputStream());
out = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
/* Reads the HTTP request and responds */
public void run() {
String request = null;
String fileName = null;
StringTokenizer tok = null;
try {
/* Read HTTP request from client */
while ((request = fromClient.readLine()) != null) {
System.out.println(request);
tok = new StringTokenizer(request);
/* Extracts the file path from the GET command */
if (tok.hasMoreElements() && tok.nextToken().equals("GET")
&& tok.hasMoreElements()) {
fileName = tok.nextToken();
} else
throw new FileNotFoundException();
/* */
if (fileName.endsWith("/"))
fileName += "index.html";
/* Illegal characters, prevent access to super directories */
if (fileName.indexOf("..") >= 0 || fileName.indexOf('|') >= 0
|| fileName.indexOf(':') >= 0 || fileName.indexOf('~') >= 0) {
error(FORBIDDEN, "Forbidden Access", fileName);
}
else
if (new File(fileName).isDirectory()) {
fileName = fileName.replace('\\', '/');
send.close();
return;
}
/* File name is ROOT_DIR + file name */
fileName = ROOT_DIR + fileName;
/* Create file */
File file = new File(fileName);
if (file.isDirectory()) {
fileName = fileName + "index.html";
}
/* File does not exist */
if (file.exists()){
/* Determines the MIME type of the file */
String mimeType = getMimeType(file);
/* Sends the file */
sendFile(file, mimeType, fileName);
client.close();
}
else
error(NOT_FOUND, "404 File Not Found", fileName);
}
}
catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
catch (IOException e){
System.err.println(e.getMessage());
}
}
/* Sends the requested file to the client */
public void sendFile(File file, String fileType, String fileName) {
try {
// Buffer must not be to low, => fragments
int length = (int) file.length();
FileInputStream fileIn = new FileInputStream(fileName);
byte[] bytes = new byte[length];
/* Write until bytes is empty */
while ((length = fileIn.read(bytes)) != -1 ){
out.write(bytes, 0, length);
out.flush();
out.writeBytes(OK);
out.writeBytes("Server: Jakobs Web Server v1.0");
out.writeBytes("Content-Type: " + fileType + "\r\n");
out.writeBytes("Content-Length: " + length + "\r\n");
out.writeBytes("");
}
send.close();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
/* Sends the header response to the client */
public void sendHeaderResponse(String code, String fileType){
try {
out.writeBytes(code);
out.writeBytes("Server: Jakobs Web Server v1.0");
out.writeBytes("Content-Type: " + fileType + "\r\n");
out.writeBytes("");
}
catch (IOException e){
System.err.println(e.getMessage());
}
}
/* Sends error response to the client */
public void error(String code, String error, String fileName){
System.err.println(error +
"\nFile Requested: " + fileName);
/* Sends the error code header */
sendHeaderResponse(code, fileName);
/* Sends the error message and cause to client */
send.print("<html><head><title>" + error + "</title></head><body>");
send.print("<h1>" + error + "</h1>\r\n");
send.println("Location: /" + fileName + "/\r\n");
send.println("Exception Cause: " + error + "\r\n");
send.print("Start Page");
send.print("</body>\"</html>");
send.flush();
send.close();
}
/* Finds out the MIME type of the requested file */
public String getMimeType(File f) {
String file = f.toString();
String type = "";
if (file.endsWith(".txt")) {
type = "text/txt";
} else if (file.endsWith(".html") || file.endsWith("htm")) {
type = "text/html";
} else if (file.endsWith(".jpg")) {
type = "image/jpg";
} else if (file.endsWith(".png")) {
type = "image/png";
} else if (file.endsWith(".jpeg")) {
type = "image/jpeg";
} else if (file.endsWith(".gif")) {
type = "image/gif";
} else if (file.endsWith(".pdf")) {
type = "application/pdf";
} else if (file.endsWith(".mp3")) {
type = "audio/mpeg";
} else if (file.endsWith(".class")){
type = "application/octet-stream";
} else if (file.endsWith(".mp4")){
type = "video/mp4";
}
return type;
}
}
Make sure that you write e.g. HTTP/1.1 404 Not Found to the client, not just the 400.
Actually no, your problem is that you don't end the response properly. The browser keeps receiving data and shows no response code received. Let me see how this can be fixed in your code.
Also, you use two wrapper streams around client.getOutputStream() to send data to the client (send and out). Not sure why you do this. This looks weird. You should use just one wrapper stream. And you never close out, probably that's your problem, that's why the browser thinks the response is not yet fully received. Try to use one stream and handle it properly.
OK, here is your code fixed.
import java.io.*;
import java.net.Socket;
import java.util.StringTokenizer;
/**
* Web Server Request Handler.
* Created on 2015-02-16.
*/
public class RequestHandler implements Runnable {
/*
TODO ( ) Problem 1
TODO ( ) Problem 2
TODO ( ) Problem 3
TODO (X) Index page for first page.
TODO (X) Read and download images & other files
TODO ( ) Fix header responses
TODO ( ) Error responses
*/
private String
OK = "HTTP/1.0 200 OK",
NOT_FOUND = "HTTP/1.0 404 Not Found",
BAD_REQUEST = "HTTP/1.0 400 Bad Request",
FORBIDDEN = "HTTP/1.0 403 Forbidden",
SERVER_ERROR = "HTTP/1.0 500 Internal Server Error";
private String ROOT_DIR;
private Socket client;
private PrintStream send;
private DataInputStream fromClient;
// private DataOutputStream out;
RequestHandler(Socket client, String ROOT_DIR) {
this.client = client;
this.ROOT_DIR = ROOT_DIR;
try {
send = new PrintStream(client.getOutputStream());
fromClient = new DataInputStream(client.getInputStream());
// out = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
/* Reads the HTTP request and responds */
public void run() {
String request = null;
String fileName = null;
StringTokenizer tok = null;
try {
/* Read HTTP request from client */
while ((request = fromClient.readLine()) != null) {
System.out.println(request);
tok = new StringTokenizer(request);
/* Extracts the file path from the GET command */
if (tok.hasMoreElements() && tok.nextToken().equals("GET")
&& tok.hasMoreElements()) {
fileName = tok.nextToken();
} else
throw new FileNotFoundException();
/* */
if (fileName.endsWith("/"))
fileName += "index.html";
/* Illegal characters, prevent access to super directories */
if (fileName.indexOf("..") >= 0 || fileName.indexOf('|') >= 0
|| fileName.indexOf(':') >= 0 || fileName.indexOf('~') >= 0) {
error(FORBIDDEN, "Forbidden Access", fileName);
}
else
if (new File(fileName).isDirectory()) {
fileName = fileName.replace('\\', '/');
send.close();
return;
}
/* File name is ROOT_DIR + file name */
fileName = ROOT_DIR + fileName;
/* Create file */
File file = new File(fileName);
if (file.isDirectory()) {
fileName = fileName + "index.html";
}
/* File does not exist */
if (file.exists()){
/* Determines the MIME type of the file */
String mimeType = getMimeType(file);
/* Sends the file */
sendFile(file, mimeType, fileName);
client.close();
}
else
error(NOT_FOUND, "404 File Not Found", fileName);
}
}
catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
catch (IOException e){
System.err.println(e.getMessage());
}
}
/* Sends the requested file to the client */
public void sendFile(File file, String fileType, String fileName) {
try {
// Buffer must not be to low, => fragments
int length = 0; // (int) file.length();
FileInputStream fileIn = new FileInputStream(fileName);
byte[] bytes = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
/* Write until bytes is empty */
while ((length = fileIn.read(bytes)) != -1 ){
bos.write(bytes, 0, length);
// send.write(bytes, 0, length);
// send.flush();
}
bos.flush();
bos.close();
byte[] data1 = bos.toByteArray();
System.out.print(new String(data1));
send.print(OK);
send.print("");
send.print("Server: Jakobs Web Server v1.0");
send.print("Content-Type: " + fileType + "\r\n");
send.print("Content-Length: " + data1.length + "\r\n");
send.println("");
send.write(data1, 0, data1.length);
send.println("");
send.flush();
send.close();
fileIn.close();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
/* Sends the header response to the client */
public void sendHeaderResponse(String code, String fileType){
try {
send.print(code);
send.print("Server: Jakobs Web Server v1.0");
send.print("Content-Type: " + fileType + "\r\n");
send.print("");
send.println();
}
catch (Exception e){
System.err.println(e.getMessage());
}
}
/* Sends error response to the client */
public void error(String code, String error, String fileName){
System.err.println(error +
"\nFile Requested: " + fileName);
/* Sends the error code header */
sendHeaderResponse(code, fileName);
// send.println("ERROR");
/* Sends the error message and cause to client */
send.print("<html><head><title>" + error + "</title></head><body>");
send.print("<h1>" + error + "</h1>\r\n");
send.println("Location: /" + fileName + "/\r\n");
send.println("Exception Cause: " + error + "\r\n");
send.print("Start Page");
send.print("</body></html>");
send.flush();
send.close();
}
/* Finds out the MIME type of the requested file */
public String getMimeType(File f) {
String file = f.toString();
String type = "";
if (file.endsWith(".txt")) {
type = "text/txt";
} else if (file.endsWith(".html") || file.endsWith("htm")) {
type = "text/html";
} else if (file.endsWith(".jpg")) {
type = "image/jpg";
} else if (file.endsWith(".png")) {
type = "image/png";
} else if (file.endsWith(".jpeg")) {
type = "image/jpeg";
} else if (file.endsWith(".gif")) {
type = "image/gif";
} else if (file.endsWith(".pdf")) {
type = "application/pdf";
} else if (file.endsWith(".mp3")) {
type = "audio/mpeg";
} else if (file.endsWith(".class")){
type = "application/octet-stream";
} else if (file.endsWith(".mp4")){
type = "video/mp4";
}
return type;
}
}
I am able to connect Ftp server. My requirement is to check if the path that will be shown after login into the server is writable in the ftp server.
Below code is not checking File remotefile = new File(pwd)
public StringBuffer verifyMath(String host, String uname, String password, String cType){
String MathString = "FTPHost:[" + host + "];uname[" + uname + "];cType[" + cType + "]";
StringBuffer mBuffer = new StringBuffer();
FileInputStream fis = null;
FTPClient client = new FTPClient();
try {
client.connect(host);
boolean login = client.login(uname, password);
client.getReplyCode(); //230
if (login == true) {
log.debug("Connection established...");
String pwd = client.printWorkingDirectory();
File remotefile = new File(pwd);
boolean rmtfile = remotefile.canWrite();
boolean rmtdir = remotefile.isDirectory();
if(!(remotefile.isDirectory() && remotefile.canWrite())) {
mBuffer.append(MathLogger.raiseError(MathString, "Math is not Writable"));
}
boolean logout = client.logout();
if (logout) {
log.debug("Connection close...");
}
} else {
mBuffer.append(MathLogger.raiseError(MathString, "Connection failed."));
}
} catch (IOException e) {
mBuffer.append(MathLogger.raiseError(MathString, e));
} finally {
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return mBuffer;
}
mlistFile (or possibly mlistDir) is probably the API you are looking for to call on the remote directory. That returns an FTPFile object that has the permission info. Of course these will only work if the FTP server supports RFC 3659 extensions.
So something like:
FTPFile remoteDir = client.mlistFile(client.printWorkingDirectory());
if (remoteDir.hasPermission(FTPFile.USER_ACCESS,FTPFile.WRITE_PERMISSION)) {
...
}
I use a thread to serve the client but when I remove the command handler.out.flush (on Server class), the thread hangs. I've tried searching on google but still not helping. I think the problem lies in the communications socket but I still have not got the right solution.
I want to make a simple login and registration functions so i used 2 class, Server and MysqlConn. The Server class receives incoming data (user profile - username, password, etc) from the client over the socket. After receiving, the data will be sent to MysqlConn class. The function of MysqlConn class is to check against the data and access my sql database to match them. If data and database match, then login process is succsses.
The format of data sent by the client is:
"login."+"name."+ "password." +"\n";
The following is the contents of Server class:
public class Server {
public static void main(String[] args)throws IOException, InstantiationException,
IllegalAccessException {
ServerSocket servsocket = null;
Socket sock = null;
try {
servsocket = new ServerSocket(28000);
while(true){
sock = servsocket.accept();
System.out.println(servsocket.isBound());
ChatThread thread = new ChatThread(sock);
String portnum = Integer.toString(sock.getPort());
thread.run(portnum);
}
} catch (IOException ioe) {
}
finally{
try {
servsocket.close();
} catch (IOException ioe) {
}
}
}
}
class ChatThread extends Thread{
static Vector<ChatThread> chatthread = new Vector<ChatThread>(10);
private BufferedReader in;
private PrintWriter out;
public ChatThread (Socket socket) throws IOException {
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(
new OutputStreamWriter(socket.getOutputStream())); }
public void run(String portnum){
String line;
synchronized(chatthread) {
chatthread.addElement(this); }
try {
line = in.readLine()+portnum;
String[] teksmasuk = line.split("\\.");
for(int i = 0; i < chatthread.size(); i++) {
synchronized(chatthread) {
ChatThread handler =
(ChatThread)chatthread.elementAt(i);
handler.out.println(line + "\r");
handler.out.flush();
if
(teksmasuk[0].contentEquals("reg")||teksmasuk[0].contentEquals("login")
||teksmasuk[0].contentEquals("logout")) {
if(teksmasuk[0].contentEquals("reg")){
}
else
if(teksmasuk[0].contentEquals("login")){
}
MysqlConn sqlcon = new MysqlConn();
String hasil = sqlcon.register(line);
}
else{
}
}
}
} catch(IOException ioe) {
ioe.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
finally {
synchronized(chatthread) {
chatthread.removeElement(this);
}
}
}
}
MysqlConn class:
public class MysqlConn{
String dbn = "chat_db";
String URL = "jdbc:mysql://localhost/"+dbn ;
String usr = "root";
String pwd = "";
private String result;
boolean checkname = false;
boolean checkemail = false;
boolean checkpass = false;
private Connection con = null;
private String dbnama;
private String dbpass;
public String register(String line) throws InstantiationException,
IllegalAccessException, IOException, ClassNotFoundException{
String[] messagein =
line.split("\\.");
MysqlConn regs = new MysqlConn();
regs.login(messagein);
return result;
}
public void login (String[] messagein) throws InstantiationException,
IllegalAccessException{
if(messagein[0].contentEquals("login")) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(URL,usr,pwd);
Statement statement =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rslset = statement.executeQuery("select * from user");
int rs = statement.executeUpdate("update user set port="+
"'"+messagein[3] +"'" + "where nama = "
+ "'" + messagein[1] + "'" + "and password = " + "'"
+messagein[2] +"'" );
MysqlConn regs = new MysqlConn();
regs.check_status_login(messagein);
} catch (ClassNotFoundException e) {
System.out.println("Error #1:" + e.getMessage());
System.exit(0);
} catch(SQLException e){
System.out.println("Error #2:" + e.getMessage());
System.exit(0);
}
}
}
public void check_status_login (String[] messagein) throws InstantiationException,
IllegalAccessException, ClassNotFoundException{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(URL,usr,pwd);
Statement statement =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rslset = statement.executeQuery("select * from user");
while(rslset.next()) {
String dbname = rslset.getString("nama");
String dbpass = rslset.getString("password");
if((messagein[1].contentEquals(dbnama))){
+ messagein[1]+ "\r" + "Password from database: "+dbpass + "\r" +
"Password from client: "+ messagein[2]+ "\n");
checknama = true;
}
else if (messagein[2].contentEquals(dbpass)){
checkpass = true;
}
}
} catch (SQLException e1) {
+ e1);
}
if (!checknama){
hasil = "gagal";
}
else if (!checkpass)
{
hasil = "gagal";
}
else {
hasil = "login sukses";}
}
}
The java docs clearly say that the constructor you are using for PrintWriter will not cause automatic flushing. This means that you nead to call flush to send data out of the printwriter manually. Alternatively you can do
out = new PrintWriter( new OutputStreamWriter(socket.getOutputStream()) , true );
to enable automatic flushing. I generally prefer to do flush streams manually anyways.
As far as your question regarding your "application gets stuck" , you will need to provide more information such as how many clients connected and what exactly happens before the system hangs
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPFile;
import java.io.*;
public class FTPUpload{
public static boolean uploadfile(String server,String username,String Password,String source_file_path,String dest_dir){
FTPClient ftp=new FTPClient();
try {
int reply;
ftp.connect(server);
ftp.login(username, Password);
System.out.println("Connected to " + server + ".");
System.out.print(ftp.getReplyString());
reply = ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP server refused connection.");
return false;
}
System.out.println("FTP server connected.");
InputStream input= new FileInputStream(source_file_path);
ftp.storeFile(dest_dir, input);
System.out.println( ftp.getReplyString() );
input.close();
ftp.logout();
} catch(Exception e) {
System.out.println("err");
e.printStackTrace();
return false;
} finally {
if(ftp.isConnected()) {
try {
ftp.disconnect();
} catch(Exception ioe) {
}
}
}
return true;
}
public static void main(String[] args) {
FTPUpload upload = new FTPUpload();
try {
upload.uploadfile("192.168.0.210","muruganp","vm4snk","/home/media/Desktop/FTP Upload/data.doc","/fileserver/filesbackup/Emac/");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Am using the above code to upload a file named "data.doc" in the server location 192.168.0.210.
The destination location of my server is fileserver/filesbackup/Emac/.
But I end up receiving the error "553 Could not create file" although the server gets connected successfully. I suspect that I am giving the destination format in a wrong way. Kindly let me know what has to be done to resolve the issue?
The problem is that you try to upload the file to a directory. You should rather specifiy the destination filename, not the destination directory.
Does it work when you try the same in another FTP client?
[Update]
Here is some (untested, since I don't have an FTP server) code that does the error handling better and in a shorter form.
package so3972768;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
public class FtpUpload {
private static void check(FTPClient ftp, String cmd, boolean succeeded) throws IOException {
if (!succeeded) {
throw new IOException("FTP error: " + ftp.getReplyString());
}
}
private static String today() {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}
public void uploadfile(String server, String username, String Password, String sourcePath, String destDir) throws IOException {
FTPClient ftp = new FTPClient();
ftp.connect(server);
try {
check(ftp, "login", ftp.login(username, Password));
System.out.println("Connected to " + server + ".");
InputStream input = new FileInputStream(sourcePath);
try {
String destination = destDir;
if (destination.endsWith("/")) {
destination += today() + "-" + new File(sourcePath).getName();
}
check(ftp, "store", ftp.storeFile(destination, input));
System.out.println("Stored " + sourcePath + " to " + destination + ".");
} finally {
input.close();
}
check(ftp, "logout", ftp.logout());
} finally {
ftp.disconnect();
}
}
public static void main(String[] args) throws IOException {
FtpUpload upload = new FtpUpload();
upload.uploadfile("192.168.0.210", "muruganp", "vm4snk", "/home/media/Desktop/FTP Upload/data.doc", "/fileserver/filesbackup/Emac/");
}
}