需求:在从From文件copy到To文件时,From文件被系统锁住,但是可以对它进行读写。我需要每次清空From文件,然后把系统写给From文件的4098个字节copy给To文件。第一次copy的时候,From文件时4098个字节。第二次的时候虽然把From文件清空了,但是数据流中依然有4089个空白字符。也就是第二次的时候From文件里有4098X2个字节。copy到To文件里的时候,文件有4098个空白符。
解决办法:主要去除输出流byte[]里的0元素。
代码:
private static void copyFile(String src, String des) {
File file1 = new File(src);
File fileDir=new File(des);
String topath = des + file1.getName();
File file2 = new File(topath);
if(!fileDir.exists()){
fileDir.mkdirs();
}
if(file2.exists()) {
file2.delete();
}
try{
InputStream inStream = new FileInputStream(src);
FileOutputStream fs = new FileOutputStream(topath);
byte[] buffer = new byte[4098];
byte[] bufferTarget = new byte[4098];
//int length;
int byteread=0;
int intFrom = 0;
int intEnd = 0;
int bytesum=0;
while ((bytesum=inStream.read(buffer,0,buffer.length)) != -1) {
for (int i = 0; i < bytesum; i++) {
if (0 !=(buffer[i])) {
intFrom = i;
for (int j = intFrom; j < bytesum;j++) {
if (0 == (buffer[j])) {
intEnd = j;
break;
}else if(j == bytesum-1) {
intEnd = bytesum;
}
}
//bufferTarget = new byte[intEnd-intFrom];
byteread= intEnd-intFrom;
System.arraycopy(buffer, intFrom, bufferTarget, 0, intEnd-intFrom);
break;
}else if (i == bytesum) {
byteread = 0;
System.arraycopy(buffer, 0, bufferTarget, 0, 0);
}
}
fs.write(bufferTarget, 0, byteread);
intFrom = 0;
intEnd = 0;
}
if (inStream != null) {
inStream.close();
}
if (fs != null){
fs.close();
}
}catch(IOException e){
e.printStackTrace();
}
}