title: Reading a file in java by a delimeter
body: <p>I have an image file with another file appended to the end of it, separated by a string delimiter. What I'm trying to do is separate the 2 files in java to write the file appended to the end into it's own file, I've tried a few solutions however they either corrupted the file or were hopelessly inefficient. Could someone point me in the right direction please?</p>
  
  <p>Here's the best solution I have so far, it almost works but corrupts the file slightly. </p>
  
  <pre><code>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 &lt; 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;
  
      }
  </code></pre>