天天看点

RandomAccessFile 读写文件内容,去除乱码

一、开发过程中遇到问题:

(1)文件内容只能等长替换,如果文件内容少了就会乱行。

解决办法:我主要是进行xml文件内容解析的,用添加随机字符串的方式进行了解决,这样既不影响文件内容解析,也把问题解决了。

二、代码:

public class FileUtils {

public static void readWriteFile(String filePath) {

RandomAccessFile raf = null;

try {

raf = new RandomAccessFile(filePath, "rw");

String line = null;

long lastPoint = 0;

int length=0;

while ((line = raf.readLine()) != null) {

String str = verifyXML(line);

long ponit = raf.getFilePointer();

length=line.length()-str.length();

str=getRandomChar(length,str);

raf.seek(lastPoint);

raf.writeBytes(str);

lastPoint = ponit;

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

raf.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

public static String verifyXML(String in) {

StringBuffer out = new StringBuffer();

char current;

if (in == null || ("".equals(in)))

return "";

for (int i = 0; i < in.length(); i++) {

current = in.charAt(i);

if ((current==0x9)||(current==0xA)||(current==0xD)

||((current>=0x20)&&(current<=0xD7FF))

||((current>=0xE000)&&(current<=0xFFFD))

||((current>=0x10000)&&(current<=0x10FFFF))){

out.append(current);

}

}

return out.toString();

}

public static String getRandomChar(int length,String str) {  

char[] chr = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',   

'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',   

'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };  

Random random = new Random();  

StringBuffer sb = new StringBuffer(str);  

for (int i = 0; i < length; i++) {  

sb.append(chr[random.nextInt(62)]);  

}  

return sb.toString();  

}

public static void main(String[] args) {

String filePath="D://test.xml";

readWriteFile(filePath);

}

}