我从客户端收到XML
个文件。我有另一个包含Base-64
编码数据的文件,我将其嵌入XML文件中的一个元素中。完成所有这些合并后,我需要将文件内容作为string
或DOM
对象返回,因为InputStream
将无效。
但最终合并的文件最后有null character
,这会导致文件被处理为XML
时出现问题。我怎么能摆脱它。这就是我合并文件的方式。
public Object merge(List<File> files) throws Exception {
System.out.println("merge with arguments is called");
if(files == null || files.isEmpty() || files.size()<2){
throw new IllegalArgumentException("File list cannot be null/empty and minimum 2 files are expected");
}
File imageFile = getImageFile(files);
File indexFile = getIndexFile(files);
File inProcessFile = new File("temp/" + indexFile.getName().replaceFirst("[.][^.]+$", "") + ".xml");
File base64EncodedFile = toBase64(imageFile);
/* Write from index file everything till attachment data to inProcess file*/
Scanner scanner = new Scanner(indexFile).useDelimiter("\\s*<AttachmentData>\\s*");
FileWriter writer = new FileWriter(inProcessFile);
writer.append(scanner.next());
/* Write <AttachmentData> element into inProcess file */
writer.append("<AttachmentData>");
/* Write base64 encoded image data into inProcess file */
IOUtils.copy(new FileInputStream(base64EncodedFile), writer);
/* Write all data from </AttachmentData> element from index file into inProcess file */
String fileAsString = IOUtils.toString(new BufferedInputStream(new FileInputStream(indexFile)));
String afterAttachmentData = fileAsString.substring(fileAsString.indexOf("</AttachmentData>"));
InputStream input = IOUtils.toInputStream(afterAttachmentData);
IOUtils.copy(input, writer);
/* Flush the file, processing completed */
writer.flush();
writer.close();
System.out.println("Process completed");
}
private File getIndexFile(List<File> files) {
for(File file:files){
String extension = FilenameUtils.getExtension(file.getName());
if(extension.equalsIgnoreCase(IDX_FILE_EXT))
return file;
}
throw new IllegalArgumentException("Index file doesn't exist or cannot be read.");
}
private File getImageFile(List<File> files) {
for(File file:files){
String extension = FilenameUtils.getExtension(file.getName());
if(extension.equalsIgnoreCase(IMG_FILE_EXT))
return file;
}
throw new IllegalArgumentException("Image file doesn't exist or cannot be read.");
}
private File toBase64(File imageFile) throws Exception {
System.out.println("toBase64 is called");
Base64InputStream in = new Base64InputStream(new FileInputStream(imageFile), true);
File f = new File("/temp/" + imageFile.getName().replaceFirst("[.][^.]+$", "") + ".txt");
Writer out = new FileWriter(f);
IOUtils.copy(in, out);
return f;
}
请帮助我理解如何修复产生空字符的代码
答案 0 :(得分:3)
修复生成它的代码,可能是删除部分或全部代码。要找到这个,你应该问自己以下问题:
根据OP稍后生成的信息,如果文件总是包含空字符,最简单的解决方案是替换行:
String afterAttachmentData = fileAsString.substring(fileAsString.indexOf("</AttachmentData>"));
与
String afterAttachmentData = fileAsString.substring(fileAsString.indexOf("</AttachmentData>"),fileAsString.length()-1);
但是,从长远来看,最好是检查客户端是否在其结尾处生成了空字符,如果是,建议他们更正生成它的代码,以便XML文档有效。