项目需要,不使用IO流,只能通过服务器端传字符串发送给客户端,进行文件的下载操作。同时,文件的上传工作也通过传递字符串的方式进行的。
感谢小白和冲~
以下是具体代码。
/**
* 根据文件获得文件的bytes的字符串格式
*
* @param filePath
* @return
*/
public static String getFileBytes(String filePath) throws AppException {
StringBuilder sb = null;
byte[] btArray = null;
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
File file = new File(filePath);
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
btArray = bos.toByteArray();
sb = new StringBuilder();
for (int i = 0; i < btArray.length; i++) {
byte bt = btArray[i];
sb.append(bt);
sb.append(',');
}
sb = sb.replace(sb.length() - 1, sb.length() - 1, "");
} catch (FileNotFoundException e) {
throw new AppException(CommonEnum.IOERROR.getKey(),
CommonEnum.IOERROR.getValue());
} catch (IOException e) {
throw new AppException(CommonEnum.IOERROR.getKey(),
CommonEnum.IOERROR.getValue());
} finally {
try {
if (fis != null) {
fis.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException e) {
// TODO log
}
}
return sb.toString();
}
/**
* 根据刚刚生成的byte数组转换的String,生成文件
*/
public static void creatFile(String fileContext, String fileName)
throws AppException {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
file = new File(fileName);
File paraFile = file.getParentFile();
if (!paraFile.exists()) {
paraFile.mkdirs();
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
String[] split = fileContext.toString().split(",");
byte[] tt = new byte[split.length];
for (int i = 0; i < split.length; i++) {
tt[i] = new Byte(split[i]);
}
bos.write(tt);
} catch (Exception e) {
throw new AppException(CommonEnum.IOERROR.getKey(),
CommonEnum.IOERROR.getValue());
} finally {
try {
if (bos != null) {
bos.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
// TODO LOG
}
}
}