2015. 10. 8. 14:00 JAVA

서비스중인 파일을 실시간 값을 바꿔 올려야 할 필요가 있을 때 사용 

사용되는 라이브러리 

commons-net-3.3.jar

여기서 삽질은 ... FTP로 다운로드 받아서 파일로 저장해서 다시 읽어 들여서 파일 수정하고 파일 올렸더니 

인코딩 문제로 ...


그래서 다운받아 원하는 부분 수정하고 저장하는 방법으로 수정하니깐 된다 



import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.text.SimpleDateFormat;

import java.util.Arrays;

import java.util.regex.Matcher;

import java.util.regex.Pattern;


import org.apache.commons.net.ProtocolCommandEvent;

import org.apache.commons.net.ProtocolCommandListener;

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.net.ftp.FTPClient;

import org.apache.commons.net.ftp.FTPConnectionClosedException;

import org.apache.commons.net.ftp.FTPReply;


public class BatChFTPCategoryVersionnew {


final String SERVER_DOWNLOAD_FILE_TEMP = "info_";

final String SERVERINFO_REMOTE = "/was/resin3/webapps/ROOT/info.jsp";


String username = "admin";

String password = "password";


String local;

String remote;

String servers[] = {

"111.222.333.444","111.222.333.444","111.222.333.444" };

String dateChange;


/**

* @param args

*           

*/


public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println(Arrays.toString(args));


new BatChFTPCategoryVersionnew(args);

}


public BatChFTPCategoryVersionnew(String[] args) {


{

System.out.println("BATCH_SERVERINFO");


remote = SERVERINFO_REMOTE;

dateChange = (String) (new SimpleDateFormat("yyyyMMddHHmmss").format(System.currentTimeMillis()));

try {

if (callFtp(servers[1], false, "UTF-8"))

logicFtp();


} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


System.out.println("dfadsf");

}


public void logicFtp() {


for (int i = 0; i < servers.length; i++) {

if (!callFtp(servers[i], true, "UTF-8"))

break;


}


}


public boolean callFtp(String server, boolean writeFile, String encoding) {


boolean binaryTransfer = false, error = false;

FTPClient ftp;

ftp = new FTPClient();

ftp.setControlEncoding(encoding);

ftp.addProtocolCommandListener(new ProtocolCommandListener() {

@Override

public void protocolReplyReceived(ProtocolCommandEvent arg0) {


printLog("receive : " + arg0.getMessage());

}


@Override

public void protocolCommandSent(ProtocolCommandEvent arg0) {


if (!arg0.getCommand().equals("PASS"))

printLog("send : " + arg0.getCommand() + " => " + arg0.getMessage());

}

});


try {

int reply;

ftp.connect(server);

printLog("Connected to " + server + ".");


// After connection attempt, you should check the reply code to

// verify

// success.

reply = ftp.getReplyCode();


if (!FTPReply.isPositiveCompletion(reply)) {

ftp.disconnect();

printLog("FTP server refused connection.");

return false;// System.exit(1);

}

} catch (IOException e) {

if (ftp.isConnected()) {

try {

ftp.disconnect();


} catch (IOException f) {

// do nothing

}

}

printLog("Could not connect to server.");

e.printStackTrace();

return false;// System.exit(1);

}


__main: try {

if (!ftp.login(username, password)) {

printLog("LOGIN FAIL");

ftp.logout();

ftp.disconnect();

error = true;

break __main;

}

printLog("LOGIN SUCCESS");


ftp.setFileType(FTP.ASCII_FILE_TYPE);


ftp.enterLocalPassiveMode();


String tempPath = System.getProperty("user.dir").replace("\\src", "") + "\\" + SERVER_DOWNLOAD_FILE_TEMP

+ dateChange + ".jsp";

System.out.println(tempPath);

if (writeFile) {


FileInputStream input = new FileInputStream(new File(tempPath));


boolean fcheck = ftp.storeFile(remote, input);

input.close();

System.out.println("remote >>>>>>>>>>>>>>>>>>>>>>>>>\n " + remote);

System.out.println("fcheck >>>>>>>>>>>>>>>>>>>>>>>>>\n " + fcheck);


} else {


String remoteFile = SERVERINFO_REMOTE;


File f = new File(tempPath);

if (f.exists())

f.delete();


InputStream inputStream = ftp.retrieveFileStream(remoteFile);

byte[] bytesArray = new byte[inputStream.available()];

inputStream.read(bytesArray);


{


String str = new String(bytesArray, "UTF-8");

Pattern p = Pattern.compile("\"categoryVersion\".*:.*\"[0-9]{14}\"");

Matcher m = p.matcher(str);

if (m.find()) {

String s = m.group(0);

str = str.replace(s, "\"categoryVersion\"" + ":\"" + dateChange + "\"");

System.out.println("**************************\n" + str);

}

OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(f));

outputStream2.write(str.getBytes("UTF-8"));

outputStream2.close();

inputStream.close();

if (str.length() == 0)

error = true;


File fcheck = new File(tempPath);

System.out.println("exists " + fcheck.exists() + " length " + fcheck.length());

if (!fcheck.exists() || fcheck.length() == 0)

error = true;

}


}


ftp.logout();

} catch (Exception e) {

error = true;

printLog("Server closed connection error." + e.toString());


e.printStackTrace();

} finally {

if (ftp.isConnected()) {

try {

ftp.disconnect();

} catch (IOException f) {

// do nothing

}

}

}

if (error)

printLog("Server end connection ERROR ");


printLog("===========================================================");

return !error;

// System.exit(error ? 1 : 0);

} //


public void printLog(String str) {

System.out.println(str);

}

}



컴파일 배치 

d:

cd D:\PROJECT\tempworkspace\BatChFTPCategoryVersionnew 


javac -cp libs\commons-net-3.3.jar src\BatChFTPCategoryVersionnew .java

cd src

java -classpath "D:\PROJECT\tempworkspace\BatChFTPCategoryVersionnew \libs\commons-net-3.3.jar;" BatChFTPCategoryVersionnew


'JAVA' 카테고리의 다른 글

jsp  (0) 2015.04.04
이클립스 워크 스페이스 삭제후 에러 발생  (0) 2014.12.03
서버 확인후 메시지 보내기  (0) 2014.10.20
java 이미지 바이트 조합  (0) 2014.01.09
자바 정렬  (0) 2011.12.01
posted by 욱이다