2012-04-06 5 views
0

이미지 파일의 끝에는 문자열 구분 기호로 구분 된 다른 파일이 추가됩니다. 내가 뭘 하려는지 자바 파일의 끝에 첨부 파일을 작성하는 두 개의 파일을 분리하는 것입니다, 나는 그들 중 하나가 파일을 손상하거나 절망적으로 비효율적 인 몇 가지 솔루션을 시도했지만. 누군가 올바른 방향으로 나를 가르쳐 주시겠습니까?delimeter로 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; 

    } 
+0

당신에게 수 당신이 그것을 어떻게하려고하는지 보여주는 몇몇 코드를 게시하시오. – casablanca

+1

문자열이 추가되면 유효한 이미지 파일이되기를 기대합니까? –

+0

지금까지 내가 가지고있는 코드를 추가했습니다. – Yawn

답변

1

파일을 문자열이 아닌 바이트 배열로 조작하는 것이 좋습니다. 따라서 바이트 순서가 어디에서 시작하는지 찾아야합니다. 물론

byte[] fileData = // read the file into a byte array 
byte[] separator = separatorString.getBytes(); 
int index = 0; 
for (;;) { 
    int start = index; 
    index = findIndexOf(fileData, separator, start); 
    if (index == -1) break; 
    byte[] nextImage = new byte[index - start + 1]; 
    System.arrayCopy(fileData, start, nextImage, 0, nextImage.length); 
    saveAsImage(nextImage); 
    index += separator.length; 
} 

당신은 (단지 String.indexOf 구현에 봐) findIndexOf(byte[] where, byte[] what, int startIndex)를 구현해야합니다. 나는 그것이 도움이되기를 바랍니다.

+0

왜 스캐너를 사용하지 않습니까? 문자 파일이 아니기 때문에 – Jon

+1

입니다. 그리고 문자열로 취급 할 때 손상됩니다. –

+0

정말 확실합니까? 이 같은 이미지 처리 기억,하지만 그것은 PHP되었을 수도 있습니다. 한 번에 전체 이미지를 읽을 수 있으므로 이미지가 손상되지 않을 것이라고 확신합니다. – Jon

1

ScanneruseDelimiter() 방법으로 이것을 수행합니다. 기본적으로 :

Scanner in = new Scanner(new File(your_file_name)); 
in.useDelimiter(START_OF_FILE_DATA); 

String first = in.next(); // Read the first part 
String seconds = in.next(); // Read the second part 

// Save the separate files 
+0

바이트 배열로 읽어들이는 대신 문자열에 넣으면 데이터가 손상됩니다. – Yawn

+0

글쎄, 어떤 경우에는 잘 작동 할 수 있습니다. 그러나 다른 경우에는 이미지 부분의 '구분 기호'를 읽을 수 있습니다 (이진 부분이기 때문에 '구분 기호'이진 표현과 같은 이진을 포함 할 수 있습니다). –

0
import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

import com.google.common.io.Files; 

    public class FileExtractor { 

    private static final int START_OF_FILE_DATA = 0x1C; 
    private static final String TEST_FILE_NAME = "test.txt"; 

    public static void main(String[] args) throws IOException {//test 
     String separator = String.valueOf((char) START_OF_FILE_DATA); 
     String bigFile = "file one" + separator + "second file" + separator + "file No. 3"; 
     Files.write(bigFile.getBytes(), new File(TEST_FILE_NAME));//create big file in project directory 

     new FileExtractor().extractFile(TEST_FILE_NAME); 
    } 

    public void extractFile(String bigFile) { 
     try (FileInputStream fis = new FileInputStream(bigFile);) { 

      List<byte[]> files = new ArrayList<byte[]>(); 
      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

      int in; 
      while ((in = fis.read()) != -1) {//read 1 byte from file until the file ends 
       if (in == START_OF_FILE_DATA) {//START_OF_FILE_DATA have length 1 byte. For longer you need to remake it. 
        files.add(baos.toByteArray()); 
        baos.reset(); 
       } 
       baos.write(in);//beware, START_OF_FILE_DATA will be included in the file 
      } 

      files.add(baos.toByteArray()); 

      for (byte[] file : files) 
       System.out.println("next file:\n" + new String(file)); 

     } catch (IOException e) { 
      System.out.println(e.getMessage()); 
     } 
    } 
} 

출력 :
다음 파일 :
파일 하나
다음 파일 :
두 번째 파일
다음 파일 :
파일 3 호