一直以来SAP与JAVA对接的相关资料甚少,最近遇到一个ABAP与JAVA文件传输的问题觉得比较典型,特此记录下。
由于情况特殊,两者之间无法用文件流进行数据传递,数次交流后发现ABAP给出的文件实际上是一段十六进制的字符串。接下来就比较简单了,用最笨的方法解决问题~
上码~
将拿到的字符串转换为byte数组
/**
* 字符串转byte
* @param c
* @return
*/
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* 字符串转byte数组
* @param str
* @return
*/
public static byte[] toBytes(String str){
if (str == null || "".equals(str)) {
return null;
}
str = str.toUpperCase();
int length = str.length() / 2;
char[] hexChars = str.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
转为byte数组后转回原文件
/**
* byte数组转文件
* @param data
* @param path
*/
public static void byteToFile(byte[] data,String path){
if(data.length<3||path.equals("")) return;
try{
FileOutputStream imageOutput = new FileOutputStream(new File(path));
imageOutput.write(data, 0, data.length);
imageOutput.close();
} catch(Exception e) {
e.printStackTrace();
}
}
ABAP传输的字符串部分txt文件时尾部会填充空白(即0000...),如下:
5B46554E4354494F4E5D0D0A436F6D6D616E643D2F480D0A0D0A5469746C653D44656275676765720D0A547970653D53797374656D436F6D6D616E64000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
这个方法用来去除空白,以保证生成的的文件不会乱码(部分文件,如doc、docx、xls、xlsx等文件不能使用,否则会导致文件不完整!如若不存在此类问题,请直接跳过)
/**
* 去除无用部分
* @param str
* @return
*/
public static String format(String str){
StringBuilder stringBuilder=new StringBuilder();
for(int i=0;i<str.length();i+=2){ //十六进制 两位一组
if(i+2<=str.length()){
String s=str.substring(i,i+2);
if (!s.equals("00")){
stringBuilder.append(s);
}
}
}
return stringBuilder.toString();
}
测试~~
public static void main(String[] args) {
try {
String res= toCode.convertToHex(new File("C:\\Users\\Administrator\\Desktop\\关于更改2019年党员党性教育培训班行前会召开时间的通知.doc"));
//res=format(res);
byte[] stringHex = toBytes(res);
byteToFile(stringHex, "C:\\Users\\Administrator\\Desktop\\test.doc");
} catch (IOException e) {
e.printStackTrace();
}
}
这里需要注意一下,生成的文件格式一定要和原文件一致!!!
这里再提供一个文件转十六进制的工具类,用于本地测试
public static String convertToHex(File file) throws IOException {
InputStream is = new FileInputStream(file);
int value = 0;
StringBuilder sbHex = new StringBuilder();
while ((value = is.read()) != -1) {
sbHex.append(String.format("%02X ", value));
}
is.close();
return sbHex.toString().replaceAll(" ","");
}
public static void main(String[] args) throws IOException{
String res=convertToHex(new File("C:\\Users\\Administrator\\Desktop\\关于更改2019年党员党性教育培训班行前会召开时间的通知.doc"));
System.out.println(res);
}
此方法通过本地测试以及正式服务端验证均可完美运行,无毒无污染,请放心食用~~
本人经历描述,大佬勿喷~