??xml version="1.0" encoding="utf-8" standalone="yes"?>
l一接口Q?/p>
public interface HelloApi { public void sayHello(); }
一、gq初始化Q?/p>
/** * 延迟初始化Bean * 延迟初始化也叫做惰性初始化Q指不提前初始化BeanQ而是只有在真正用时才创建及初始化Bean? * 配置方式很简单只需?lt;bean>标签上指?“lazy-init?属性gؓ“true”即可gq初始化Bean? */ public class DiLazyInit implements HelloApi{ public void sayHello() { System.out.println("say DiInitDestory"); } public DiLazyInit(){ System.out.println("初始?DiInitDestory"); } }
配置延迟初始化:
<!-- 延迟初始化Bean 延迟初始化也叫做惰性初始化Q指不提前初始化BeanQ而是只有在真正用时才创建及初始化Bean? 配置方式很简单只需?lt;bean>标签上指?“lazy-init?属性gؓ“true”即可gq初始化Bean?--> <bean id="lazyinitDi" class="com.diinit.DiLazyInit" lazy-init="true"> </bean>
junit q行试Q?/p>
@Test public void testLazyInit(){ ApplicationContext context = new ClassPathXmlApplicationContext("initdepends.xml"); HelloApi lazyInit = context.getBean("lazyinitDi",HelloApi.class); lazyInit.sayHello(); System.out.println(""); }
注意q个时候的输出l果Q?/p>
初始?DiLazyInit
say DiLazyInit
二?可以指定初始化和销毁的序
/* 使用depends-on 是指 指定Bean初始化及销毁时的顺序,使用depends-on属性指定的Bean要先初始化完? * 后才初始化当前BeanQ由于只有“singleton”Bean能被Spring理销毁,所以当指定的Bean都是“singleton? * Ӟ使用depends-on属性指定的Bean要在指定的Bean之后销毁? * “decorator”指定了“depends-on”属性ؓ“lazyinitDi”,所以在“decorator”Bean初始化之前要先初 * 始化“lazyinitDi”,而在销毁“lazyinitDi”之前先要销毁“decorator”,大家注意一下销毁顺序,与文档上的不W? * “depends-on”属性可以指定多个BeanQ若指定多个Bean可以用?”、?”、空格分剌Ӏ? * * 那“depends-on”有什么好处呢Q? * 主要是给出明的初始化及销毁顺序,比如要初始化“decorator”时要确保“lazyinitDi”Bean的资源准备好了, * 否则使用“decorator”时会看不到准备的资源;而在销毁时要先在“decorator”Bean的把对“helloApi”资源的引用? * 放掉才能销毁“lazyinitDi”,否则可能销?“lazyinitDi”时而“decorator”还保持着资源讉KQ造成资源不能释放或释N误? */ public class ApiDecorator implements HelloApi{ private HelloApi helloApi; public ApiDecorator(){ System.out.println("初始?ApiDecorator"); } public void sayHello() { System.out.println("say ApiDecorator"); helloApi.sayHello(); } public HelloApi getHelloApi() { return helloApi; } public void setHelloApi(HelloApi helloApi) { this.helloApi = helloApi; } }
配置xml指定初始化和销毁顺序:
<!-- 初始化及销毁时的顺? “decorator”指定了“depends-on”属性ؓ“lazyinitDi”,所以在“decorator”Bean初始化之? 要先初始化“lazyinitDi”,而在销毁“lazyinitDi”之前先要销毁“decorator”,大家注意一下销毁顺?--> <bean id="decorator" class="com.diinit.ApiDecorator" depends-on="lazyinitDi"> <property name="helloApi"> <ref bean="lazyinitDi" /> </property> </bean>
junit q行试Q?/p>
@Test public void testLazyInit(){ ApplicationContext context = new ClassPathXmlApplicationContext("initdepends.xml"); HelloApi lazyInit = context.getBean("lazyinitDi",HelloApi.class); lazyInit.sayHello(); System.out.println(""); } @Test public void testDependsOn(){ ApplicationContext context= new ClassPathXmlApplicationContext("initdepends.xml"); HelloApi depends = context.getBean("decorator",HelloApi.class); depends.sayHello(); }
注意q个时候的输出l果Q?/p>
初始?DiLazyInit
初始?ApiDecorator //也是上面同样的测试函?testLazyInit()Q同L配置 q句是多打印出来?/strong>
say DiLazyInit
初始?DiLazyInit
初始?ApiDecorator
say ApiDecorator
say DiLazyInit
q突然多出来的打印结果,说明q行了ApiDecorator的对象的创徏Q?/p>
但是在第一个配|中也没涉及刊WApiDecorator cȝ加蝲Q注? ?/p>
什么原因造成的呢Q?span style="color: #0000ff;">是一U隐藏的注入Q?l箋探烦?...
一、构造器注入方式Q?/strong>
Q?Q通过?<constructor-arg>”标{ref属性来引用其他Bean
Q?Q通过?<constructor-arg>”标{?lt;ref>标签来引用其他BeanQ用bean属性来指定引用的Bean
二、setter注入方式Q?/strong>
Q?Q通过?<property>”标{ref属性来引用其他Bean
Q?Q通过?<property>”标{?lt;ref>标签来引用其他BeanQ用bean属性来指定引用的Bean
public class HelloDiBean implements HelloApi{ private HelloApi helloApi; private HelloApi helloApi2; public HelloDiBean(HelloApi helloApi){ this.helloApi = helloApi; } public void sayHello() { helloApi.sayHello(); helloApi2.sayHello(); } public HelloApi getHelloApi2() { return helloApi2; } public void setHelloApi2(HelloApi helloApi2) { this.helloApi2 = helloApi2; } }
配置注入引用其他的bean
<!-- 引用其他的beanq行注入 --> <bean id="helloBean" class="com.dilist.HelloDiBean"> <constructor-arg index="0" ref="mapBean" /> <property name="helloApi2"> <ref bean="properBean" /> </property> </bean>
其他引用bean 的高U用法:
/** * Springq提供了另外两种更高U的配置方式Q?lt;ref local=”?>?lt;ref parent=”?>Q? * Q?Q?lt;ref local=”?>配置方式Q用于引用通过<bean id=”beanName?gt;方式中通过id属性指定的BeanQ? * 它能利用XML解析器的验证功能在读取配|文件时来验证引用的Bean是否存在? * 因此如果在当前配|文件中有相互引用的Bean可以采用<ref local>方式从而如果配|错误能在开发调试时发现错误? * Q?Q?lt;ref parent=”?>配置方式Q用于引用父容器中的BeanQ不会引用当前容器中的BeanQ? * 当然父容器中的Bean和当前容器的Bean是可以重名的Q获取顺序是直接到父容器找? */ public class HelloHigh implements HelloApi{ private HelloApi helloApi; private HelloApi helloApi2; public HelloHigh(HelloApi helloApi){ this.helloApi = helloApi; } public void sayHello() { helloApi.sayHello(); System.out.println(""); helloApi2.sayHello(); } public HelloApi getHelloApi2() { return helloApi2; } public void setHelloApi2(HelloApi helloApi2) { this.helloApi2 = helloApi2; } }
helloworld.xmlQ?/span>
<!-- 注入propertiescd --> <bean id="properBean" class="com.dilist.HelloDiProperties"> <property name="properties"> <props value-type="int" merge="default"><!-- 虽然指定value-type,但是不v作用 --> <prop key="1">1sss</prop> <!-- Properties 建和值都是Stringcd --> <prop key="2">2</prop> </props> </property> <property name="properties2"> <value> <!-- 分隔W可以是 “换行”、“;”、“,?不徏议该方式Q优先选择W一U方?--> 1=11 2=22;<!-- q样的分隔符好像没用 --> 3=33, 4=44 </value> </property> </bean> <!-- Springq提供了另外两种更高U的配置方式Q?lt;ref local=”?>?lt;ref parent=”?> --> <bean id="helloHigh" class="com.dilist.HelloHigh"> <constructor-arg index="0"><ref local="properBean" /></constructor-arg> <property name="helloApi2"><ref parent="properBean" /></property> </bean>
helloworldParent.xmlQ?/span>
<!-- 注入propertiescd --> <bean id="properBean" class="com.dilist.HelloDiProperties"> <property name="properties"> <props value-type="int" merge="default"><!-- 虽然指定value-type,但是不v作用 --> <prop key="1">2dss</prop> <!-- Properties 建和值都是Stringcd --> <prop key="2">3aas</prop> </props> </property> <property name="properties2"> <value> <!-- 分隔W可以是 “换行”、“;”、“,?不徏议该方式Q优先选择W一U方?--> 1=111 2=222;<!-- q样的分隔符好像没用 --> 3=333, 4=444 </value> </property> </bean>
调用?利用加蝲父容器的方式Q注入父容器中的BeanQ?/p>
@Test public void testDiBeanHigh() { // 以classes为根目录v // d配置文g实例化一个Ioc容器 // 初始化父容器 ApplicationContext parentContext = new ClassPathXmlApplicationContext( "helloworldParent.xml"); // 初始化当前容? ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "helloworld.xml" }, parentContext); // 构?+ setter注入 引用其他的bean注入 HelloApi helloApi = context.getBean("helloHigh", HelloApi.class); helloApi.sayHello(); }
import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; public class HelloWorld extends ClassLoader implements Opcodes{ public static void main(String[] args) { ClassWriter cw = new ClassWriter(0); cw.visit(V1_1, ACC_PUBLIC, "Example", null, "java/lang/Object", null); MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mw.visitVarInsn(ALOAD, 0); mw.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); mw.visitInsn(RETURN); mw.visitMaxs(1, 1); mw.visitEnd(); mw = cw.visitMethod(ACC_PUBLIC+ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null); mw.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mw.visitLdcInsn("Hello World!"); mw.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); mw.visitInsn(RETURN); mw.visitMaxs(2, 2); mw.visitEnd(); byte[] code = cw.toByteArray(); FileOutputStream fos; try { fos = new FileOutputStream("Example.class"); fos.write(code); fos.close(); HelloWorld loader = new HelloWorld(); Class exampleClass = loader .defineClass("Example", code, 0, code.length); exampleClass.getMethods()[0].invoke(null, new Object[] { null }); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
cglib 动态生成class q进行拦?/pre>
public class MyClass { public void print() { System.out.println("I'm in MyClass.print!"); } } import net.sf.cglib.proxy.Callback; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class Main { public static void main(String[] args) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(MyClass.class); enhancer.setCallback((Callback) new MethodInterceptorImpl()); MyClass my = (MyClass) enhancer.create(); my.print(); } private static class MethodInterceptorImpl implements MethodInterceptor { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { // log something System.out.println(method + " intercepted!"); proxy.invokeSuper(obj, args); return null; } } }
已有 1 人发表留aQ猛?>>q里<<-参与讨论
ITeye推荐
import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import sun.net.TelnetInputStream; import sun.net.TelnetOutputStream; import sun.net.ftp.FtpClient; import sun.net.ftp.FtpLoginException; public class FtpUtil { /** * @param args */ public static void main(String[] args) { FtpUtil ftp = new FtpUtil(); ftp.connect("10.16.12.75", 21, "ftpusr", "ftpusr"); try { // 上传目录下文?q可以递归到子目录 // ftp.upPathFile(new File("D:\\ALSC"), "ALSC/"); // 下蝲目录下多个文?q可以递归到子目录 //ftp.downPathFile("/opt/ftp/outgoing/cs/", "D:/outgoing/csvc"); // 切换目录 ftp.setPath("/opt/ftp/book"); System.out.println(ftp.getDir()); for (String file : ftp.getFileNameList()) { System.out.println(file); } // 切换到父U目? ftp.up(); // 创徏多目? // ftp.createDir("aa/bb/cc"); ftp.setPath("ftpTest"); // 删除文g ftp.deleteFile("bbb.bmp"); System.out.println(ftp.getDir()); for (String file : ftp.getFileNameList()) { System.out.println(file); } // 上传 下蝲单个文g ftp.uploadFile("c:/aaa.bmp", "bbb.bmp"); ftp.downloadFile("bbb.bmp", "c:/bbb"); List<String> list = ftp.getFileList(); for (String file : list) { System.out.println(file); } ftp.setPath("/opt/ftp/outgoing/cs"); String patternStr = "^CSGET_[0-9]{4}_0085_"+"20120926"+"_[0-9]{3}"; // qoQ获取目录下的文件列? list = ftp.getFileList(new CSFilter(patternStr)); for (String file : list) { System.out.println(file); } //下蝲 qo后的文g ftp.downPathFile("/opt/ftp/outgoing/cs/", "D:/outgoing/csvc",new CSFilter(patternStr)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ftp.close(); } private FtpClient ftpClient = null; /** * 打开q接 * * @param hostname * @param port * @param username * @param passwd * @return */ public void connect(String hostname, int port, String username, String passwd) { String msg = ""; try { ftpClient = new FtpClient(hostname, port); ftpClient.login(username, passwd); ftpClient.binary(); msg = "q接成功Q?; } catch (FtpLoginException e) { msg = "dLp|Q可能是用户名密码错误!"; e.printStackTrace(); } catch (IOException e) { msg = "dLp|Q请验端品是否正!"; e.printStackTrace(); } catch (SecurityException e) { msg = "无权q接LQ主认是否有权限连接主机!"; e.printStackTrace(); } System.out.println(msg); } /** * 关闭q接 */ public void close() { if (ftpClient == null) { return; } try { ftpClient.closeServer(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 重命? * * @param oldName * @param newName * @return */ public boolean renameFile(String oldName, String newName) { boolean result = false; try { this.ftpClient.rename(oldName, newName); result = true; } catch (IOException e) { e.printStackTrace(); } return result; } /** * 取得相对于当前连接目录的某个目录下所有文件列? * * @param path * @return */ public List getFileList(String path) { List list = new ArrayList(); DataInputStream dis; try { dis = new DataInputStream(ftpClient.nameList(this.getDir() + path)); String filename = ""; while ((filename = dis.readLine()) != null) { list.add(filename); } } catch (IOException e) { e.printStackTrace(); } return list; } /** * d文g列表 * * @return * @throws IOException */ public List<String> getFileList() throws IOException { List<String> fileList = new ArrayList<String>(); InputStreamReader isr = null; BufferedReader br = null; try { isr = new InputStreamReader(this.ftpClient.list()); br = new BufferedReader(isr); String fileName = ""; while (true) { fileName = br.readLine(); if (fileName == null) { break; } fileList.add(fileName); } } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (isr != null) { try { isr.close(); } catch (IOException e) { e.printStackTrace(); } } } return fileList; } /** * d文g列表 * * @return * @throws IOException */ public List<String> getFileList(FileFilter filter) throws IOException { List<String> fileList = new ArrayList<String>(); InputStreamReader isr = null; BufferedReader br = null; try { isr = new InputStreamReader(this.ftpClient.list()); br = new BufferedReader(isr); String fileName = ""; while (true) { fileName = br.readLine(); if (fileName == null) { break; } if ((filter == null) || filter.accept(new File(fileName))) fileList.add(fileName); } } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (isr != null) { try { isr.close(); } catch (IOException e) { e.printStackTrace(); } } } return fileList; } /** * 获取文g名列? * * @return * @throws IOException */ public List<String> getFileNameList() throws IOException { List<String> fileNameList = new ArrayList<String>(); InputStreamReader isr = null; BufferedReader br = null; try { isr = new InputStreamReader(this.ftpClient.nameList(this.getDir())); br = new BufferedReader(isr); String fileName = ""; while (true) { fileName = br.readLine(); if (fileName == null) { break; } fileNameList.add(fileName); } } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (isr != null) { try { isr.close(); } catch (IOException e) { e.printStackTrace(); } } } return fileNameList; } /** * 讄路径 切换目录 * * @param path * @return */ public boolean setPath(String path) { if (this.ftpClient != null) { try { ftpClient.cd(path); return true; } catch (IOException e) { e.printStackTrace(); return false; } } else { return false; } } /** * 判断是否为目? * * @param line * @return */ public boolean isDir(String line) { return line.startsWith("d"); } /** * 查文件夹在当前目录下是否存在 * * @param dir * @return */ public boolean isDirExist(String dir) { String pwd = ""; try { pwd = ftpClient.pwd(); ftpClient.cd(dir); ftpClient.cd(pwd); } catch (Exception e) { return false; } return true; } /** * 获取当前路径 * * @return * @throws IOException */ public String getDir() throws IOException { return this.ftpClient.pwd(); } /** * 向上 切换到父U目? * * @throws IOException */ public void up() throws IOException { if ("/".equals(ftpClient.pwd()) || "http://".equals(ftpClient.pwd())) { return; } this.ftpClient.cdUp(); } /** * 删除文g * * @param fileName * @return */ public void deleteFile(String fileName) { ftpClient.sendServer("dele " + fileName + "\r\n");// q个地方一定要注意 加上 \r\n try { if (ftpClient.readServerResponse() != 250) System.out.println("删除异常"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 在当前目录下创徏文g? * * @param dir * @return * @throws Exception */ public boolean createDir(String dir) { try { ftpClient.ascii(); StringTokenizer s = new StringTokenizer(dir, "/"); // sign s.countTokens(); String pathName = ftpClient.pwd(); while (s.hasMoreElements()) { pathName = pathName + "/" + (String) s.nextElement(); try { ftpClient.sendServer("MKD " + pathName + "\r\n"); } catch (Exception e) { e = null; return false; } ftpClient.readServerResponse(); } ftpClient.binary(); return true; } catch (IOException e1) { e1.printStackTrace(); return false; } } /** * 上传文g * * @param localFile * @param targetFileName * @return */ public boolean uploadFile(String localFile, String targetFileName) { boolean result = false; if (this.ftpClient == null) { return false; } TelnetOutputStream tos = null; RandomAccessFile sendFile = null; DataOutputStream dos = null; try { File file = new File(localFile); sendFile = new RandomAccessFile(file, "r"); sendFile.seek(0); tos = this.ftpClient.put(targetFileName); dos = new DataOutputStream(tos); int ch = 0; while (sendFile.getFilePointer() < sendFile.length()) { ch = sendFile.read(); dos.write(ch); } result = true; } catch (Exception ex) { result = false; } finally { if (tos != null) { try { tos.close(); } catch (IOException e) { e.printStackTrace(); } } if (dos != null) { try { dos.close(); } catch (IOException e) { e.printStackTrace(); } } if (sendFile != null) { try { sendFile.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } /** * 上传文g * * @param localFile * @param targetFileName * @return */ public boolean uploadFile(File localFile, String targetFileName) { boolean result = false; if (this.ftpClient == null) { return false; } TelnetOutputStream tos = null; RandomAccessFile sendFile = null; DataOutputStream dos = null; try { sendFile = new RandomAccessFile(localFile, "r"); sendFile.seek(0); tos = this.ftpClient.put(targetFileName); dos = new DataOutputStream(tos); int ch = 0; while (sendFile.getFilePointer() < sendFile.length()) { ch = sendFile.read(); dos.write(ch); } result = true; } catch (Exception ex) { result = false; } finally { if (tos != null) { try { tos.close(); } catch (IOException e) { e.printStackTrace(); } } if (dos != null) { try { dos.close(); } catch (IOException e) { e.printStackTrace(); } } if (sendFile != null) { try { sendFile.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } /** * 上传本地目录下的所有文件到服务器上 * * @param srcPath * @param tagPath * @param level * 递归的? * @return * @see [cR类#Ҏ、类#成员] */ public boolean upPathFile(File srcPathFile, String tagPath) { buildList(tagPath.substring(0, tagPath.lastIndexOf("/"))); boolean result = true; try { File temp[] = srcPathFile.listFiles(); for (int i = 0; i < temp.length; i++) { if (temp[i].isDirectory()) { if (tagPath.lastIndexOf('/') > 0) { result = upPathFile(temp[i], tagPath + temp[i].getName() + "/"); } else { result = upPathFile(temp[i], tagPath + "/" + temp[i].getName() + "/"); } } else { if (tagPath.lastIndexOf('/') > 0) { result = uploadFile(temp[i], tagPath + temp[i].getName()); } else { result = uploadFile(temp[i], tagPath + "/" + temp[i].getName()); } } } } catch (Exception e) { e.printStackTrace(); } return result; } /** * 下蝲文g * * @param srcFileName * @param targetFileName * @return */ public boolean downloadFile(String srcFileName, String targetFileName) { if (this.ftpClient == null) { return false; } TelnetInputStream tis = null; RandomAccessFile getFile = null; boolean result = true; try { File file = new File(targetFileName); getFile = new RandomAccessFile(file, "rw"); getFile.seek(0); tis = this.ftpClient.get(srcFileName); DataInputStream dis = new DataInputStream(tis); int ch = 0; while (true) { ch = dis.read(); if (ch < 0) { break; } getFile.write(ch); } getFile.close(); } catch (IOException e) { result = false; } finally { if (getFile != null) { try { getFile.close(); } catch (IOException e) { e.printStackTrace(); } } if (tis != null) { try { tis.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } /** * 下蝲文g * * @param srcFileName * @param targetFileName * @return */ public boolean downloadFile(String srcFileName, File targetFileName) { if (this.ftpClient == null) { return false; } TelnetInputStream tis = null; RandomAccessFile getFile = null; boolean result = true; try { getFile = new RandomAccessFile(targetFileName, "rw"); getFile.seek(0); tis = this.ftpClient.get(srcFileName); DataInputStream dis = new DataInputStream(tis); int ch = 0; while (true) { ch = dis.read(); if (ch < 0) { break; } getFile.write(ch); } getFile.close(); } catch (IOException e) { result = false; } finally { if (getFile != null) { try { getFile.close(); } catch (IOException e) { e.printStackTrace(); } } if (tis != null) { try { tis.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } /** * 下蝲q程目录下的所有文件到本地 * * @param srcPathFile * q程目录文g * @param tagPath * 本地存放目录 * @return * @throws IOException * @see [cR类#Ҏ、类#成员] */ public boolean downPathFile(String srcPath, String tagPath) throws IOException { boolean result = true; File tagFile = new File(tagPath); tagFile.mkdirs(); setPath(srcPath); String tempPath = ""; List<String> list = getFileList(); for (int i = 0; i < list.size(); i++) { String currPath = list.get(i); String fileName = getFileName(currPath); String currPathFul = getDir() + "/" + fileName; if (tagPath.lastIndexOf('/') > 0) { tempPath = tagPath + currPathFul.substring(currPathFul.lastIndexOf("/"), currPathFul.length()); } else { tempPath = tagPath + "/" + currPathFul.substring(currPathFul.lastIndexOf("/"), currPathFul.length()); } if (isDir(currPath)) { srcPath = currPathFul + "/"; downPathFile(srcPath, tempPath); } else { srcPath = currPathFul; downloadFile(srcPath, tempPath); } } return result; } /** * 下蝲q程目录下的所有文件到本地Q过滤规? * * @param srcPathFile * q程目录文g * @param tagPath * 本地存放目录 * @param fileFilter * 下蝲qo文g * @return * @throws IOException * @see [cR类#Ҏ、类#成员] */ public boolean downPathFile(String srcPath, String tagPath, FileFilter fileFilter) throws IOException { boolean result = true; File tagFile = new File(tagPath); tagFile.mkdirs(); setPath(srcPath); String tempPath = ""; List<String> list = getFileList(fileFilter); for (int i = 0; i < list.size(); i++) { String currPath = list.get(i); String fileName = getFileName(currPath); String currPathFul = getDir() + "/" + fileName; if (tagPath.lastIndexOf('/') > 0) { tempPath = tagPath + currPathFul.substring(currPathFul.lastIndexOf("/"), currPathFul.length()); } else { tempPath = tagPath + "/" + currPathFul.substring(currPathFul.lastIndexOf("/"), currPathFul.length()); } if (isDir(currPath)) { srcPath = currPathFul + "/"; downPathFile(srcPath, tempPath, fileFilter); } else { srcPath = currPathFul; downloadFile(srcPath, tempPath); } } return result; } public String getFileName(String line) { int i; String filename = (String) parseLine(line).get(8); for (i = 9; i < parseLine(line).size(); i++) { filename = filename + " " + ((String) parseLine(line).get(i)); } return filename; } // 处理getFileList取得的行信息 private ArrayList parseLine(String line) { ArrayList s1 = new ArrayList(); StringTokenizer st = new StringTokenizer(line, " "); while (st.hasMoreTokens()) { s1.add(st.nextToken()); } return s1; } /** * 从FTP文g服务器上下蝲文gSourceFileNameQ到本地destinationFileName 所有的文g名中都要求包括完整的路径名在? * * @param SourceFileName * String * @param destinationFileName * String * @throws Exception */ public void downFile(String SourceFileName, String destinationFileName) throws Exception { ftpClient.binary(); // 一定要使用二进制模? TelnetInputStream ftpIn = ftpClient.get(SourceFileName); byte[] buf = new byte[204800]; int bufsize = 0; FileOutputStream ftpOut = new FileOutputStream(destinationFileName); while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) { ftpOut.write(buf, 0, bufsize); } ftpOut.close(); ftpIn.close(); } /** * 从FTP文g服务器上下蝲文gQ输出到字节数组? * * @param SourceFileName * String * @return byte[] * @throws Exception */ public byte[] downFile(String SourceFileName) throws Exception { ftpClient.binary(); // 一定要使用二进制模? TelnetInputStream ftpIn = ftpClient.get(SourceFileName); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); byte[] buf = new byte[204800]; int bufsize = 0; while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) { byteOut.write(buf, 0, bufsize); } byte[] return_arraybyte = byteOut.toByteArray(); byteOut.close(); ftpIn.close(); return return_arraybyte; } /** * 上传文g到FTP服务?destination路径以FTP服务器的"/"开始,带文件名?上传文g只能使用二进制模式, * 当文件存在时再次上传则会覆盖 * * @param source * String * @param destination * String * @throws Exception */ public void upFile(String source, String destination) throws Exception { buildList(destination.substring(0, destination.lastIndexOf("/"))); ftpClient.binary(); // 此行代码必须攑֜buildList之后 TelnetOutputStream ftpOut = ftpClient.put(destination); TelnetInputStream ftpIn = new TelnetInputStream(new FileInputStream( source), true); byte[] buf = new byte[204800]; int bufsize = 0; while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) { ftpOut.write(buf, 0, bufsize); } ftpIn.close(); ftpOut.close(); } /** * JSP中的上传到FTP服务? 上传文g只能使用二进制模式,当文件存在时再次上传则会覆盖 字节数组做ؓ文g的输入流, * 此方法适用于JSP中通过request输入来直接上传文g在RequestUploadcM调用了此ҎQ? * destination路径以FTP服务器的"/"开始,带文件名 * * @param sourceData * byte[] * @param destination * String * @throws Exception */ public void upFile(byte[] sourceData, String destination) throws Exception { buildList(destination.substring(0, destination.lastIndexOf("/"))); ftpClient.binary(); // 此行代码必须攑֜buildList之后 TelnetOutputStream ftpOut = ftpClient.put(destination); ftpOut.write(sourceData, 0, sourceData.length); // ftpOut.flush(); ftpOut.close(); } /** * 在FTP服务器上建立指定的目?当目录已l存在的情下不会影响目录下的文g,q样用以判断FTP * 上传文g时保证目录的存在目录格式必须?/"根目录开? * * @param pathList * String * @throws Exception */ public void buildList(String pathList) { try { ftpClient.ascii(); StringTokenizer s = new StringTokenizer(pathList, "/"); // sign int count = s.countTokens(); String pathName = ""; while (s.hasMoreElements()) { pathName = pathName + (String) s.nextElement(); try { ftpClient.sendServer("XMKD " + pathName + "\r\n"); } catch (Exception e) { e = null; } int reply = ftpClient.readServerResponse(); pathName = pathName + "/"; } ftpClient.binary(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }
qoQ?/p>
import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.regex.Pattern; public class CSFilter implements FileFilter { private String patternStr ; //"^CSGET_[0-9]{4}_0085_"+"20120926"+"_[0-9]{3}" private Pattern pattern ; public CSVCFilter(String str){ this.patternStr = str; this.pattern = Pattern.compile(patternStr); } public boolean accept(File pathname) { String strName = pathname.getName(); if (!isDir(strName)) { strName = getFileName(strName); System.out.println(strName); return pattern.matcher(strName).matches(); } return true; } public boolean isDir(String strName) { return ((String) parseLine(strName).get(0)).indexOf("d") != -1; } public String getFileName(String line) { int i; String filename = (String) parseLine(line).get(8); for (i = 9; i < parseLine(line).size(); i++) { filename = filename + " " + ((String) parseLine(line).get(i)); } return filename; } // 处理getFileList取得的行信息 private ArrayList parseLine(String line) { ArrayList s1 = new ArrayList(); StringTokenizer st = new StringTokenizer(line, " "); while (st.hasMoreTokens()) { s1.add(st.nextToken()); } return s1; } public String getFileSize(String line) { return (String) parseLine(line).get(4); } public String getFileDate(String line) { ArrayList a = parseLine(line); return (String) a.get(5) + " " + (String) a.get(6) + " " + (String) a.get(7); } }
下蝲速度提升
public boolean downloadFile(String srcFileName, File targetFileName) { //..... //下蝲速度太慢Q用如下方式q行提升 byte[] recvbuf = new byte[1024]; while((ch = dis.read(recvbuf)) > 0){ getFile.write(recvbuf,0,ch); } // while (true) { // ch = dis.read(); // if (ch < 0) { // break; // } // getFile.write(ch); // } //... }
// 1. 分配一?ServerSocketChannel 文g描述W? serverChannel = ServerSocketChannel.open(); // 2. ?ServerSocketChannel里获取一个对于的 socket serverSocket = serverChannel.socket(); // 3. 生成一?Selector selector = Selector.open(); // 4. ?socket l定到端口上 serverSocket.bind(new InetSocketAddress(iport)); // 5. serverChannel 未非bolck serverChannel.configureBlocking(false); // 6. 通过Selector注册ServerSocketChannel: 只能注册 accept // 而SocketChannel可以注册CONNENCT,READ,WRITE ; register -> validOps // 在各个子cdC? serverChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { try { // 获得IO准备qA的channel数量 int n = selector.select(); // 没有channel准备qA,l箋执行 if (n == 0) { continue; } // 用一个iteratorq回Selector的selectedkeys Iterator it = selector.selectedKeys().iterator(); // 处理每一个SelectionKey while (it.hasNext()) { SelectionKey key = (SelectionKey) it.next(); // 判断是否有新的连接到? if (key.isAcceptable()) { // q回SelectionKey的ServerSocketChannel ServerSocketChannel server = (ServerSocketChannel) key .channel(); System.out.println("有连?); SocketChannel channel = server.accept(); registerChannel(selector, channel, SelectionKey.OP_READ); doWork(channel); } // 判断是否有数据在此channel里需要读? if (key.isReadable()) { processData(key); } } // 删除 selectedkeys it.remove(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
客户端:
//打开socket通道 SocketChannel socketChannel = SocketChannel.open(); //讄非阻塞方? socketChannel.configureBlocking(false); //打开选择? Selector selector = Selector.open(); //注册q接到服务器socket动作 socketChannel.register(selector, SelectionKey.OP_CONNECT); //q接 socketChannel.connect( new InetSocketAddress("localhost",9988)); Set<SelectionKey> selectkeySets; SelectionKey selectionKey; Iterator<SelectionKey> iterator; //与服务器通信通道 SocketChannel clientChannel ; while(true){ //选择一l徏Q其相应的通道已ؓI/O操作准备qA //此方法执行处于阻塞模式的选择操作 selector.select(TIME_OUT); //q回此选择器的已选择键集? selectkeySets = selector.selectedKeys(); iterator = selectkeySets.iterator(); while(iterator.hasNext()){ selectionKey = iterator.next(); if (selectionKey.isConnectable()) { clientChannel = (SocketChannel)selectionKey.channel(); // 判断此通道上是否正在进行连接操作? // 完成套接字通道的连接过E? if (clientChannel.isConnectionPending()) {//判断此通道上是否正在进行连接操? clientChannel.finishConnect(); //完成套接字通道的连接过E? } clientChannel.register(selector, SelectionKey.OP_WRITE); }else if (selectionKey.isReadable()) { clientChannel = (SocketChannel)selectionKey.channel(); //缓冲区清空 receiveBuffer.clear(); //d服务器发送来的数据库到缓冲区 count = clientChannel.read(receiveBuffer);//count d到的字节? if (count > 0) { clientChannel.register(selector, SelectionKey.OP_WRITE); } }else if (selectionKey.isWritable()) { sendBuffer.clear(); clientChannel = (SocketChannel)selectionKey.channel(); clientChannel.write(sendBuffer); System.out.println("客户端向服务器发送数?"+sendText); clientChannel.register(selector, SelectionKey.OP_READ); } } }
// 创徏一个非d的server端socket Q用NIO SocketAcceptor acceptor = new NioSocketAcceptor(); // 创徏接收数据的过滤器 DefaultIoFilterChainBuilder chain = acceptor.getFilterChain(); // 讑֮q个qo器一行一?\r\n)的读数据 chain.addLast("myChin", new ProtocolCodecFilter( new TextLineCodecFactory())); //讑֮服务器端的消息处理器,一个SamplMinaServerHandler对象(自己实现)l承IoHandlerAdapter acceptor.setHandler(new IoHandlerAdapter(){ //当一个客端端q结q入? @Override public void sessionOpened(IoSession session) throws Exception { // TODO Auto-generated method stub System.out.println("incomming client : "+session.getRemoteAddress()); } //当一个客L关闭? @Override public void sessionClosed(IoSession session) throws Exception { // TODO Auto-generated method stub System.out.println("on client disconnect : "+session.getRemoteAddress()); } //当客L发送的消息到达? @Override public void messageReceived(IoSession session, Object message) throws Exception { // TODO Auto-generated method stub String s = (String)message; System.out.println("收到客户端发来的消息:"+s); //试消息回l客L session.write(s+count); count ++; } private int count =0; }); //端口? int bindPort= 9988; //l定打开Q启动服务器 acceptor.bind(new InetSocketAddress(bindPort)); System.out.println("Mina Server is listing on:="+bindPort);
客户端:
// create TCP/IP connector NioSocketConnector connector = new NioSocketConnector(); // 创徏接收数据的过滤器 DefaultIoFilterChainBuilder chain = connector.getFilterChain(); // 讑֮q个qo器将一行一?/r/n)的读取数? chain.addLast("myChin", new ProtocolCodecFilter( new TextLineCodecFactory())); // 讑֮服务器端的消息处理器:一个SamplMinaServerHandler对象, connector.setHandler(new IoHandlerAdapter(){ @Override public void messageReceived(IoSession session, Object message) throws Exception { // 我们p定了服务器解析消息的规则是一行一行读?q里可转ؓString: String s = (String) message; // Write the received data back to remote peer System.out.println("服务器发来的收到消息: " + s); // 试消息回送给客户? session.write(s); } @Override public void sessionClosed(IoSession session) throws Exception { // TODO Auto-generated method stub System.out.println("one Clinet Disconnect !"); } @Override public void sessionOpened(IoSession session) throws Exception { // TODO Auto-generated method stub System.out.println("incomming client " + session.getRemoteAddress()); session.write("我来?......."); } }); // Set connect timeout. connector.setConnectTimeout(30); // q结到服务器: ConnectFuture cf = connector.connect(new InetSocketAddress("localhost", 9988)); // Wait for the connection attempt to be finished. cf.awaitUninterruptibly(); cf.getSession().getCloseFuture().awaitUninterruptibly(); connector.dispose();
分区 用时间进行分?/p>
已有 0 人发表留aQ猛?>>q里<<-参与讨论
ITeye推荐
public static int PORT = 8888; ServerSocketChannel serverChannel; ServerSocket serverSocket; Selector selector;
初始化:
// 1. 分配一?ServerSocketChannel 文g描述W? serverChannel = ServerSocketChannel.open(); // 2. ?ServerSocketChannel里获取一个对于的 socket serverSocket = serverChannel.socket(); // 3. 生成一?Selector selector = Selector.open(); // 4. ?socket l定到端口上 serverSocket.bind(new InetSocketAddress(iport)); // 5. serverChannel 未非bolck serverChannel.configureBlocking(false); // 6. 通过Selector注册ServerSocketChannel: 只能注册 accept // 而SocketChannel可以注册CONNENCT,READ,WRITE ; register -> validOps // 在各个子cdC? serverChannel.register(selector, SelectionKey.OP_ACCEPT);
开启服务:
while (true) { try { // 获得IO准备qA的channel数量 int n = selector.select(); // 没有channel准备qA,l箋执行 if (n == 0) { continue; } // 用一个iteratorq回Selector的selectedkeys Iterator it = selector.selectedKeys().iterator(); // 处理每一个SelectionKey while (it.hasNext()) { SelectionKey key = (SelectionKey) it.next(); // 判断是否有新的连接到? if (key.isAcceptable()) { // q回SelectionKey的ServerSocketChannel ServerSocketChannel server = (ServerSocketChannel) key .channel(); System.out.println("有连?); SocketChannel channel = server.accept(); registerChannel(selector, channel, SelectionKey.OP_READ); doWork(channel); } // 判断是否有数据在此channel里需要读? if (key.isReadable()) { processData(key); } } // 删除 selectedkeys it.remove(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }