-1
我收到來自客戶端的XML
文件。我有另一個文件,其中包含Base-64
編碼的數據,我將其嵌入到XML文件中的一個元素中。完成所有這些合併後,我需要將文件的內容返回爲string
或DOM
對象,返回InputStream
將不起作用。如何從java中的文件內容中刪除空字符
但是最終生成的合併文件末尾有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;
}
請幫助我明白,我怎麼能解決我的代碼產生空字符
+1,*刪除/修復*會更好。 –
請參閱我的問題的更新。我添加了代碼 –
@MartijnCourteaux感謝您的建議。 –