文件转换

public static File getIncodeFile(File file) {

String fileName = null;

String fileSuffix = null;

File incodeFile = null;

String incoding = "ISO-8859-1";

if(Common.checkFileName(file.getName())){

fileName = file.getName().split("\\_")[0]; // 文件名称

fileSuffix = file.getName().split("\\_")[1]; // 文件后缀

incodeFile = new File(Common.incodePath + fileName + "." + fileSuffix);

}else{

fileName = file.getName().split("\\_")[0]; // 文件名称

incodeFile = new File(Common.incodePath + fileName);

}

byte[] myByte = null;

FileOutputStream fos = null;

try {

fos = new FileOutputStream(incodeFile);

Object[] myObject = Common.changeFileToByte(file);

myByte = new byte[myObject.length];

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

//try {

//myByte[i] = (byte) Integer.parseInt((String) myObject[i], 16);

//} catch (Exception e) { //byte 为负数

//String hexStr = (String) myObject[i];

//myByte[i] = (byte) (Integer.parseInt(hexStr.substring(hexStr.length() - 2, hexStr.length()), 16) - 256);

//}

int a = Integer.parseInt(myObject[i]+"", 16);

myByte[i] = (byte)(a & 0xff);

}

String fileaString = new String(myByte, incoding); 

fos.write(fileaString.getBytes(incoding));  

       fos.flush();

} catch (Exception ex) {

ex.printStackTrace();

} finally {

try {

if (fos != null) {

fos.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return incodeFile;

}

public static Object[] changeFileToByte(File file) {

ArrayList<String> list = null;

BufferedReader br = null;

Object[] result = null;

try {

list = new ArrayList<String>();

br = new BufferedReader(new InputStreamReader(new FileInputStream(

file), "utf-8"));

String str = null;

while ((str = br.readLine()) != null) {

String[] Str = str.split(",");

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

list.add(Str[i]);

}

}

result = list.toArray();

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

br.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return result;

}

猜你喜欢

转载自lzk-258.iteye.com/blog/2340935