读取文件

实现功能有:

1、读取一个文件的文字,录入到另一个文件中

2、读取一个文件流,截取相应的字节,录入到另一个文件中

伪代码,如下:

/**

* 示例一

* 读取一个文件的文字,录入到另一个文件中

*/

String sendContent="F:/test3.txt";

String receiveContent="F:/test/aaa.txt";

try {

RandomAccessFile randomFile = new RandomAccessFile(sendContent, "rw");

// 将读文件的开始位置移到beginIndex位置。 

int beginIndex =0;

randomFile.seek(beginIndex);

   byte[] bytes = new byte[10];  

       int byteread = 0;  

       //一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。  将一次读取的字节数赋给byteread

       RandomAccessFile randomReceiveFile = new RandomAccessFile(receiveContent, "rw");

       randomReceiveFile.seek(randomReceiveFile.length());

       while ((byteread = randomFile.read(bytes)) != -1) {  

        System.out.write(bytes, 0, byteread);  

        //获取内容录入到另一个文件中

        randomReceiveFile.write(bytes, 0, byteread);//ok

       }  

} catch (Exception e) {

e.printStackTrace();

/**

* 示例二

* 读取一个文件流,截取相应的字节,录入到另一个文件中

*/

String sendContent="F:/test.txt";

String receiveContent="F:/test/aaa.txt";

try {

// RandomAccessFile randomFile = new RandomAccessFile(sendContent, "rw");

InputStream randomFile = new FileInputStream(sendContent);

// 将读文件的开始位置移到beginIndex位置。 

int beginIndex =0;

randomFile.skip(beginIndex);

   byte[] bytes = new byte[10];  

       int byteread = 0;  

       //一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。  将一次读取的字节数赋给byteread

       RandomAccessFile randomReceiveFile = new RandomAccessFile(receiveContent, "rw");

       randomReceiveFile.seek(randomReceiveFile.length());

       while ((byteread = randomFile.read(bytes)) != -1) {  

        System.out.write(bytes, 0, byteread);  

        //获取内容录入到另一个文件中

        randomReceiveFile.write(bytes, 0, byteread);//ok

       }  

} catch (Exception e) {

e.printStackTrace();

}

猜你喜欢

转载自yingyingsheji.iteye.com/blog/2356526
今日推荐