我有一个图像文件,其末尾附加了另一个文件,由字符串分隔符分隔。我想要做的是将java中的两个文件分开,将附加到末尾的文件写入它自己的文件中,我尝试了一些解决方案,但是它们要么损坏了文件,要么效率低下。有人可以指出我正确的方向吗?
这是迄今为止我最好的解决方案,它几乎可以工作,但会稍微损坏文件。
public class FileExtractor {
private static final String START_OF_FILE_DATA = "SOFD34qjknhwe3rjkhw";
public void extractFile(String[] files)
{
try
{
String first = readFileToString(files[0]);
Pattern p1 = Pattern.compile(START_OF_FILE_DATA + "(.*)" + START_OF_FILE_DATA + "(.*)", Pattern.DOTALL);
Matcher matcher1 = p1.matcher(first);
String filename = "";
if(matcher1.find())
{
filename = matcher1.group(1);
}
else
{
//throw exception of corrupted file
}
FileOutputStream out = new FileOutputStream(new File("buildtest/" + filename));
out.write(matcher1.group(2).getBytes("cp1251"), 0, matcher1.group(2).length());
for (int i = 1; i < files.length; i++)
{
String content = readFileToString(files[i]);
Pattern p = Pattern.compile(START_OF_FILE_DATA + "(.*)", Pattern.DOTALL);
Matcher matcher = p.matcher(content);
if(matcher.find())
{
out.write(matcher.group(1).getBytes("cp1251"), 0, matcher.group(1).length());
}
else
{
//throw exception of corrupted file
}
}
out.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
private String readFileToString(String file)
{
byte[] buffer = new byte[(int) new File(file).length()];
BufferedInputStream f = null;
try {
f = new BufferedInputStream(new FileInputStream(file));
f.read(buffer);
}
catch (Exception e)
{
}
finally
{
if (f != null) {
try {
f.close();
} catch (IOException ignored) {
}
}
}
String ret = "";
try
{
ret = new String(buffer, "cp1251");
}
catch(Exception e)
{
}
return ret;
}