6.6 读写远程文件
FttpAdapter是通过FttpReadAdapter来直接读取远程文件内容:
- FttpAdapter fa = new FttpAdapter("fttp://192.168.0.1/home/log/1.log");
- FttpReadAdapter reader = fa.getFttpReader();
- byte[] bts = reader.readAll();
上面的代码是读取整个文件的内容,如果文件内容很大,每次只读取一部分内容,需要指定FttpReadAdapter的读取范围:
- FttpReadAdapter reader = fa.getFttpReader(5,10);
- byte[] bts = reader.readAll();
上面代码表示从第5个字节,往后读10个字节。读取方示的示例还有:
❏ fa.getFttpReader(5,FileAdapter.m(8))从第5个字节往后读8M。
❏ fa.getFttpReader(5,FileAdapter.k(512))从第5个字节往后读512K。
FttpAdapter是通过FttpWriteAdapter来直接写入远程文件内容:
- FttpAdapter fa = new FttpAdapter("fttp://192.168.0.1/home/log/1.log");
- FttpWriteAdapter writer = fa.getFttpWriter();
- int r = writer.write("hello world".getBytes());
上面的FttpWriteAdapter没有指定写入范围,默认追加在文件末尾,如果需要指定范围,则应使用如下代码:
- FttpWriteAdapter writer = fa.getFttpWriter(5,10);
- 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:
- java -cp fourinone.jar; ParkServerDemo
2)在192.168.0.1机器上启动FttpServer:
- java -cp fourinone.jar; FttpServer 192.168.0.1
3)在本地运行FttpWriteReadDemo,远程读写192.168.0.1上的文件:
- java -cp fourinone.jar; FttpWriteReadDemo
完整demo源码如下:
- // FttpWriteReadDemo
- import com.fourinone.FttpAdapter;
- import com.fourinone.FttpException;
- public class FttpWriteReadDemo
- {
- public static void fttpWrite(){
- try{
- FttpAdapter fa = new FttpAdapter("fttp://192.168.0.1/home/log/1.log");
- fa.getFttpWriter().write("hello world".getBytes());
- fa.close();
- }catch(FttpException fe){
- fe.printStackTrace();
- }
- }
- public static void fttpRead(){
- try{
- FttpAdapter fa = new FttpAdapter("fttp://192.168.0.1/home/log/1.log");
- byte[] bts = fa.getFttpReader().readAll();
- System.out.println("logstr:"+new String(bts));
- byte[] hellobts = fa.getFttpReader(0,5).readAll();
- System.out.println("hellostr:"+new String(hellobts));
- fa.close();
- }catch(FttpException fe){
- fe.printStackTrace();
- }
- }
- public static void main(String[] args){
- fttpWrite();
- fttpRead();
- }
- }