2012-10-31 3 views
0

텍스트 파일을 개체로 변환 한 다음 세 가지 별도의 파일 구문 분석 함수를 사용하여 이러한 값을 다시 sqlite 데이터베이스에 삽입합니다. 그것들은 기본적으로 객체 클래스를 제외하고 모두 동일합니다. 다음과 같이리팩토링 텍스트 파일 파싱을 일괄 처리

과정은 간다 :

  1. 이 목표 테이블의 이전 기록을 모두 삭제 진행 계산에 파일의 라인 카운트 HTTP를
  2. 을 사용하여 파일을 다운로드
  3. BufferedReader를 사용하여 파일 열기
  4. 한 번에 2000 줄을 읽고이를 개체로 변환하십시오.
  5. Insert 2000 recor
을 완료 할 때까지 트랜잭션
  • 루프에서 sqlite가에 DS는

    나는 일반이 코드는 모든 클래스는 객체를 생성 한 다음를 유지하는 데 사용할 DAL 기능 결정을 위해 사용할 수 있도록하는 방법을 알아낼 수 없습니다 데이터. Java는 제 첫 번째 언어가 아니므로 모든 지침이 훌륭합니다.

    public void downloadPendingPoleInspections() { 
    
        int count; 
        String filePath; 
        Inspections inspections = Inspections.getInstance(); 
    
        filePath = Environment.getExternalStorageDirectory() + File.separator + "inspections.txt"; 
    
        try { 
    
         downloadFile("http://localhost/api/inspectionservices.aspx?o=retrieve", "pendinginspections.txt", POST_PENDING_INSPECTIONS_PROGRESS_UPDATE); 
    
         int totalInspections = getLineCount(filePath); 
    
         inspections.deleteAllPendingInspections();   
    
         File file = new File(filePath); 
         BufferedReader br = new BufferedReader(new FileReader(file)); 
         String line; 
    
         int i = 0; 
         int j = 0; 
    
         List<PendingInspection> batch = new ArrayList<PendingInspection>(); 
    
         while ((line = br.readLine()) != null) { 
          String[] values = line.split(" "); 
    
          PendingInspection pending = new PendingInspection(
            Integer.parseInt(values[0]), values[1], 
            Double.parseDouble(values[2]), 
            Double.parseDouble(values[3])); 
    
          batch.add(pending); 
          i++; 
          j++; 
    
          if (i >= 2000) { 
    
           inspections.pendingInspectionsBatchInsert(batch);     
           batch.clear(); 
           i = 0;     
          } 
         } 
    
         if (i > 0) { 
          inspections.pendingInspectionsBatchInsert(batch); 
          batch.clear(); 
         } 
    
         br.close(); 
         file.delete(); 
    
        } catch (Exception e) { 
         Log.e("SyncActivity", e.toString());    
        }  
    } 
    

    편집 : 여기

    내가 사용하고있는 코드는 다음 인터페이스와 클래스 선언은

    public interface Inspectable { 
        public int getId(); 
        public void setId(int id); 
    
        public String getLabel(); 
        public void setLabel(String label); 
    
        public double getX(); 
        public void setX(double x); 
    
        public double getY(); 
        public void setY(double y); 
    } 
    
    public class RWInspection { 
    private String id; 
    private double x; 
    private double y; 
    private String inspector; 
    private String comments; 
    private String timestamp; 
    
    
    public RWInspection(String id, double x, double y, String inspector, String comments, String timestamp) { 
         this.id = id;  
         this.x = x; 
         this.y = y; 
         this.inspector = inspector; 
         this.comments = comments; 
         this.timestamp = timestamp; 
    } 
    

    싹둑 .... getter 및 setter 구현입니다

    public class PInspection implements Inspectable{ 
        private int id; 
        private String number; 
        private double x; 
        private double y; 
    
    public PInspection(int id, String poleNumber, double x, double y) { 
        this.id = id; 
        this.number = number ; 
        this.x = x; 
        this.y = y; 
    } 
    
  • 답변

    1

    나는이를 추상적 기본 클래스와 구현으로 나누었습니다. 기본 클래스는 다음과 같습니다 각 유형에 대해

    public abstract class Downloader { 
        protected abstract void processLine(String[] line); 
        protected abstract void save(); 
        protected abstract String file(); 
    public void downloadPendingPoleInspections() { 
    
        int count; 
        String filePath; 
    
        filePath = Environment.getExternalStorageDirectory() + File.separator + file(); 
    
        try { 
    
         downloadFile("http://localhost/api/inspectionservices.aspx?o=retrieve", "pending" + file(), POST_PENDING_INSPECTIONS_PROGRESS_UPDATE); 
    
         int totalInspections = getLineCount(filePath); 
    
         File file = new File(filePath); 
         BufferedReader br = new BufferedReader(new FileReader(file)); 
         String line; 
    
         int i = 0; 
         int j = 0; 
    
    
         while ((line = br.readLine()) != null) { 
          processLine(line.split(" ")); 
          i++; 
          j++; 
    
          if (i >= 2000) { 
           save() 
           i = 0;     
          } 
         } 
    
         if (i > 0) { 
          save() 
         } 
    
         br.close(); 
         file.delete(); 
    
        } catch (Exception e) { 
         Log.e("SyncActivity", e.toString());    
        }  
    } 
    

    당신이 이런 작은 implentation 만들 처리하는 경우 :

    public class InspectionDownloader extends DownLoader { 
        Inspections inspections = Inspections.getInstance(); 
        List<PendingInspection> batch = new ArrayList<PendingInspection>(); 
    
        public InspectionDownloader() { 
         inspections.deleteAllPendingInspections(); 
        } 
    
        protected void processLine(String[] values) { 
         PendingInspection pending = new PendingInspection(
          Integer.parseInt(values[0]), values[1], 
          Double.parseDouble(values[2]), 
          Double.parseDouble(values[3])); 
         batch.add(pending); 
        } 
    
        protected void save() { 
         inspections.pendingInspectionsBatchInsert(batch); 
         batch.clear(); 
        } 
        protected String file() { 
         return "inspections.txt"; 
        } 
    } 
    

    하나는 기본 클래스에서 재사용 가능한 로직을 집중할 수있는이 방법과 특별한 논리를 작고 집중된 전문 수업으로 옮기십시오. 이 패턴을 템플리트 화 된 메소드라고합니다.파생 클래스가 응답하는 유형의 특수한 작업에 매우 초점을 맞추고 있음을 알 수 있습니다.

    +0

    그러면 다음과 같이 간단하게 호출 할 수 있습니다. InspectionDownloader d = new InspectionDownloader(); 그리고 기본 클래스 downloadPendingPoleInspections 메소드는 실제 작업을 처리 할 것인가? – eptiliom

    +0

    나는이 대답으로 갈 것이다, 고마워. – eptiliom

    1

    그들은 모두 기본적으로 개체를 제외하고 동일합니다 수업.

    일괄 처리의 일부로 생성되는 모든 개체에 공통 인터페이스가 있어야하는 것처럼 들립니다. 다음과 같이 뭔가를 권장합니다

    그런 다음 다음을 수행
    public interface Batchable { void doBatch(); } 
    

    :

    public class Foo implements Batchable {} 
    public class Bar implements Batchable {} 
    

    이제 각 클래스 doBatch에 대한 자신의 함수 본문을 구현하고 적어도 부분적으로 알 필요 멀리 추상화 한 수 클래스. 이제 한 번에 2000 개의 레코드를 유지하는 측면에서 대규모 트랜잭션에서 한 번에 모든 레코드를 밀어 넣지 마십시오. 이렇게하지 않으면 데이터 무결성 손실 위험에 처해 있습니다.

    +0

    클래스는 이미 공통 인터페이스를 구현하지만 각 클래스는 파일에서 구문 분석 할 수있는 속성의 수가 서로 다르므로 실제로 문제에 답하지 않습니다. 이 레코드는 안드로이드 타블렛에서 실행 중이며 가져올 수있는 레코드가 100,000 개를 초과 할 수 있으므로 오랜 잠재력을 가진 커밋 시간으로 인해 진행 상황을 보여줄 필요가 있습니다. – eptiliom

    +0

    데이터/클래스의 구조는 무엇입니까? 이 게시물을 원래 게시물에 추가하십시오. – Woot4Moo

    +0

    @eptiliom 한 번에 2000 개를 수행하면 아무 것도 사지 않습니다. – Woot4Moo

    관련 문제