我需要读取文件,提取字节并添加<segment></segment>
标记。然后我必须提取字节并提取<segment>
标签之间的内容。最后,标签数据将用于制作原始图像的精确副本......但我的问题是图像看起来不像原始图像。如何从Java中的字符串保存图像文件?
随着文本文件工作正常,但没有图像。
这是我的java代码。很容易:
public class MyFile {
public static void main(String[] args) {
try{
/* Read File */
File aFile= new File("infinito.jpg");
FileInputStream fis = new FileInputStream(aFile);
long sizeFichero = aFile.length();
byte []datos = new byte[(int) sizeFichero];
fis.read(datos);
fis.close();
/* Write copy file */
File copyFile = new File("infinto_COPY.jpg");
FileOutputStream fos = new FileOutputStream(copyFile);
/* Add bytes to array bytes */
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write("<segment>".getBytes());
outputStream.write(datos);
outputStream.write("</segment>".getBytes());
byte [] bytes = outputStream.toByteArray();
/* Regular Expression */
String text = new String(bytes);
String regexpr = "<segment>(.*?)</segment>";
Pattern pat = Pattern.compile(regexpr, Pattern.MULTILINE | Pattern.DOTALL);
Matcher mat = pat.matcher(text);
/* If find between <segment></segment> then write file */
if (mat.find()){
String group1 = mat.group(1);
fos.write(group1.getBytes());
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果。原件和复印件:
我怎么能做到这一点,通过分析正则表达式?
非常感谢。
为什么你会希望*用正则表达式,首先呢?其次,如果您使用XML格式的纯文本,则与图像数据不同。你不想先把它转换成二进制数据吗? –
正则表达式基本上用于java中的字符串类型的文本数据。字符串是一个'char'数组,每个'char'由两个字节组成。将文本和字节数据的混合作为一个单位输入到正则表达式引擎并不是一个好主意(恕我直言),引擎试图读取一系列'字符'。 –
''string“.getBytes()'和'new String(bytes)'使用默认平台编码,这可能与将JPEG的字节视为字符串不兼容。例如,JPEG通常(并非总是)以“ff d8 ff e0”开头,这与UTF-8完全无效。总是使用'getBytes'和'String' ctor的重写,它们采用明确的编码,并停止尝试将二进制图像文件视为文本。 –