6.6 读写远程文件

FttpAdapter是通过FttpReadAdapter来直接读取远程文件内容:

  1. FttpAdapter fa = new FttpAdapter("fttp://192.168.0.1/home/log/1.log");
  2. FttpReadAdapter reader = fa.getFttpReader();
  3. byte[] bts = reader.readAll();

上面的代码是读取整个文件的内容,如果文件内容很大,每次只读取一部分内容,需要指定FttpReadAdapter的读取范围:

  1. FttpReadAdapter reader = fa.getFttpReader(5,10);
  2. byte[] bts = reader.readAll();

上面代码表示从第5个字节,往后读10个字节。读取方示的示例还有:

❏ fa.getFttpReader(5,FileAdapter.m(8))从第5个字节往后读8M。

❏ fa.getFttpReader(5,FileAdapter.k(512))从第5个字节往后读512K。

FttpAdapter是通过FttpWriteAdapter来直接写入远程文件内容:

  1. FttpAdapter fa = new FttpAdapter("fttp://192.168.0.1/home/log/1.log");
  2. FttpWriteAdapter writer = fa.getFttpWriter();
  3. int r = writer.write("hello world".getBytes());

上面的FttpWriteAdapter没有指定写入范围,默认追加在文件末尾,如果需要指定范围,则应使用如下代码:

  1. FttpWriteAdapter writer = fa.getFttpWriter(5,10);
  2. int r = writer.write("hello world".getBytes());

上面代码表示从第5个字节开始,往后写10个字节,写入内容为"hello world",如果写入内容超出10个字节,则截断,不够则填补空位。

除readAll和write外,FttpAdapter也提供readAllSafety和writeSafety方法,它们的用法一样,但是后两者代表排它读写,主要用于并发读写。

对于数字存储,FttpAdapter也提供getIntFttpReader和getIntFttpWriter用于整型读写,操作与字节读写类似,只是写入或返回的是整数,比如:

❏ fa.getIntFttpReader(5,3)表示从第5个整数开始,往后读3个整数。

❏ fa.getIntFttpWriter().writeInt(new int[]{1,2,3})表示将一个整数数组写入文件末尾。

同样,整型读写也都提供排它读写。FttpWriteReadDemo演示了对远程文件的读写操作。

运行步骤如下:

1)启动ParkServerDemo:

  1. java -cp fourinone.jar; ParkServerDemo

2)在192.168.0.1机器上启动FttpServer:

  1. java -cp fourinone.jar; FttpServer 192.168.0.1

3)在本地运行FttpWriteReadDemo,远程读写192.168.0.1上的文件:

  1. java -cp fourinone.jar; FttpWriteReadDemo

完整demo源码如下:

  1. // FttpWriteReadDemo
  2. import com.fourinone.FttpAdapter;
  3. import com.fourinone.FttpException;
  4.  
  5. public class FttpWriteReadDemo
  6. {
  7. public static void fttpWrite(){
  8. try{
  9. FttpAdapter fa = new FttpAdapter("fttp://192.168.0.1/home/log/1.log");
  10. fa.getFttpWriter().write("hello world".getBytes());
  11. fa.close();
  12. }catch(FttpException fe){
  13. fe.printStackTrace();
  14. }
  15. }
  16.  
  17. public static void fttpRead(){
  18. try{
  19. FttpAdapter fa = new FttpAdapter("fttp://192.168.0.1/home/log/1.log");
  20. byte[] bts = fa.getFttpReader().readAll();
  21. System.out.println("logstr:"+new String(bts));
  22.  
  23. byte[] hellobts = fa.getFttpReader(0,5).readAll();
  24. System.out.println("hellostr:"+new String(hellobts));
  25.  
  26. fa.close();
  27. }catch(FttpException fe){
  28. fe.printStackTrace();
  29. }
  30. }
  31.  
  32. public static void main(String[] args){
  33. fttpWrite();
  34. fttpRead();
  35. }
  36. }