2013-03-16 2 views
-2

Android 용 앱을 만들고 있습니다. 내 응용 프로그램에는 2 개의 "for 루프"가 있습니다. 각 루프는 3200 회 반복되고 53KB의 .txt 파일 (3200 개의 행이 포함되어 있음)에 액세스하고 문자열을 각 행과 반복마다 한 행을 비교합니다. "for 루프"에는 BufferedReader(), InputStreamReader(), InputStream() 및 StringTokenizer()도 포함됩니다. 따라서 에뮬레이터에서 앱을 실행할 때 해당 기능을 처리하는 데 약 8 초가 걸립니다. 이것은 용납 될 수 없다. 어떻게하면 30 초 정도의 시간을 줄일 수 있습니까? 1 초? 감사! 편집 :이 여기 루프의 2 내 프로그램의 일부입니다 : 내가 당신이라면for() 루프를 만드는 시간을 줄이기 (안드로이드)?

else if(a==2){ 
     String z=""; 
     try{ 
      InputStream is = getAssets().open("USCOUNTIES.txt"); 
      InputStreamReader iz=new InputStreamReader(is); 
      BufferedReader bis = new BufferedReader(iz); 

      int v=0; 

      v=count("USCOUNTIES.txt");//counts number of lines in the .txt file 
     //finding no. of counties to be displayed 
      int counter=0; 
      String pos; 
      pos=Integer.toString(position); 
      try{ 
      for(int i=0;i<v;i++){ 
       z=bis.readLine(); 
       //int x=pos.length(); 
       boolean a; 
       //using stringtokenizer 
       StringTokenizer st = new StringTokenizer(z, ","); 
       String substring; 
       substring=(String) st.nextElement(); 
       a=substring.equals(pos); 
       if(a==true){ 

        counter=counter+1; 

       } 
      }}catch(Exception e){e.printStackTrace();} 
      String array1[]=new String[counter]; 

      try{ 
       InputStream ig = getAssets().open("USCOUNTIES.txt"); 
       InputStreamReader ia=new InputStreamReader(ig); 
       BufferedReader bos = new BufferedReader(ia); 
      int j=0; 
      for(int i=0;i<v;i++){ 
       z=bos.readLine(); 
       String[] split = z.split(","); 
       if(split[0].equals(pos)){ 
        array1[j]=split[1]; 
        j=j+1; 
       } 

      }} 
      catch(Exception e){e.printStackTrace();} 
+1

정직하게 말하면, 라인마다 3200 라인의 3200 파일을 읽는 데 8 초가 걸립니다. –

+0

단일 3200 파일입니다. 3200 번 반복됩니다. 당신이 가진 어떤 제안? 파일의 일부 데이터를 목록에 넣기 위해이 작업을 수행합니다. –

+7

왜 같은 파일을 다시 읽는거야 ** 3200 번 **? – CommonsWare

답변

1

, 난 단지 한 번에 모든 것을 분석하고 당신이 원하는 무엇이든 함께 할 것입니다.

이 코드 조각이 단지는 Integers의 분석 (I 의심은하지 Strings 같은 값으로 이러한 필요)을 포함하여 수행합니다

public void read() throws IOException { 
    InputStream is = getAssets().open("USCOUNTIES.txt"); 
    InputStreamReader iz=new InputStreamReader(is); 
    BufferedReader bis = new BufferedReader(iz); 
    String line = ""; 
    String firstNumber = ""; 
    String secondNumber = ""; 
    String countyName = ""; 
    StringTokenizer st = null; 
    HashMap<Pair, String> map = new HashMap<>(); 
    while((line = bis.readLine()) != null) { 
     st = new StringTokenizer(line, ","); 
     firstNumber = (String) st.nextElement(); 
     st = new StringTokenizer((String)st.nextElement(), ">"); 
     secondNumber = (String) st.nextElement(); 
     countyName = ((String) st.nextElement()); 
     countyName = countyName.substring(0, countyName.length()-1); 
     int num1 = Integer.parseInt(firstNumber); 
     int num2 = Integer.parseInt(secondNumber); 
     map.put(new Pair(num1, num2), countyName); 
    } 
} 

class Pair { 
    int num1, num2; 
    Pair(int num1, int num2) { 
     this.num1 = num1; 
     this.num2 = num2; 
    } 

    public boolean equals(Object other) { 
     if (other instanceof Pair) { 
      Pair np = (Pair) other; 
      return this.num1 == np.num1 && this.num2 == np.num2; 
     } 
     return false; 
    } 

    public int hashCode() { 
     return (Integer.valueOf(num1).hashCode() >> 13)^Integer.valueOf(num2).hashCode(); 
    }; 
} 

지금 당신은 단순히이 줄을 모든 countyName 검색 할 수 있습니다

String s = map.get(new Pair(1,69)); 

그리고 그게 내가 그건 당신이 시작 할텐데

Aleutians East를 반환합니다.

편집

이런 코드 (더 HashMap<Integer, Object> 같이) SparseArray 2D를 사용한다. 이것으로 모든 것이 첫 번째 숫자로 정렬됩니다.

public class Reader { 
    private String firstNumber = ""; 
    private String secondNumber = ""; 
    private String countyName = ""; 
    private StringTokenizer stringTokenizer = null; 
    private SparseArray<SparseArray<String>> sparseArray = new SparseArray<SparseArray<String>>(); 
    private SparseArray<String> temporarySparseArray = null; 

    public void readFromIS() throws IOException { 
     InputStream is = getAssets().open("USCOUNTIES.txt"); 
     InputStreamReader iz=new InputStreamReader(is); 
     BufferedReader bis = new BufferedReader(iz); 
     String line = null; 
     while((line = bis.readLine()) != null) { 
      readLine(line); 
     } 
    } 

    public void readFromList() { 
     String[] strings = { 
       "0,1>Autauga;", 
       "0,2>Baldwin;", 
       "0,3>Barbour;", 
       "1,69>Aleutians East;",  
       "1,68>Aleutians West;" 
     }; 
     for (String line : strings) { 
      readLine(line); 
     } 
    } 

    private void readLine(String line) { 
     stringTokenizer = new StringTokenizer(line, ","); 
     firstNumber = (String) stringTokenizer.nextElement(); 
     stringTokenizer = new StringTokenizer((String)stringTokenizer.nextElement(), ">"); 
     secondNumber = (String) stringTokenizer.nextElement(); 
     countyName = ((String) stringTokenizer.nextElement()); 
     countyName = countyName.substring(0, countyName.length()-1); 
     int num1 = Integer.parseInt(firstNumber); 
     int num2 = Integer.parseInt(secondNumber); 
     if (sparseArray.get(num1) == null) { 
      sparseArray.put(num1, new SparseArray<String>()); 
     } 
     temporarySparseArray = sparseArray.get(num1); 
     temporarySparseArray.put(num2, countyName); 
     sparseArray.put(num1, temporarySparseArray); 
     temporarySparseArray = null; 
    } 

    public void test() { 
     readFromList(); 
     String s = sparseArray.get(0).get(2); 
     SparseArray sa = sparseArray.get(0); 
     System.out.println(sa.size()); //should be 3 
     System.out.println(s); // should be Baldwin 
    } 
} 

그리고 num1로 시작하는 모든 카운티를 검색 할 수는 0, 그냥 사용하는 말 : 참고로

SparseArray<String> startingWithZero = sparseArray.get(0); 

하십시오 SparseArrayintegers에 대한 HashMap, 그래서 모든 것이 오토 박싱되어야한다 (Integer에서 int까지, 기본 유형을 HashMap에 입력 할 수 없으므로).

EDIT2 1D sparseArray의 주소를 인쇄합니다.

public void printEverythingStartingWithZero() { 
    SparseArray<String> subSparseArray = sparseArray.get(0); //You first need a 1D sparseArray 
    int key = 0; 
    for(int i = 0; i < subSparseArray.size(); i++) { 
     key = subSparseArray.keyAt(i); 
     String county = subSparseArray.get(key); //county is the String in place (0,key) 
     System.out.println(county); 
    } 
} 

당신은 앞의 0으로 먼저 1D sparseArray를 검색 할 필요가있다.

+0

이 코드를 이용해 주셔서 감사합니다! 나는 질문이있다. num1 = 1 인 모든 문자열을 반환하려면 문자열 s = map.get (new Pair (1, i))을 사용합니다. 여기서 for 루프는 0에서 3200까지 반복합니다. 그것을 달성하는 방법? –

+0

전체 목록의 하위 집합이 필요하기 때문에 어느 방향 으로든 루프해야합니다. 그러나 2D 'sparseArray'를 사용하면 가능할 수도 있습니다. Lemme 수표. – stealthjong

+0

내 생각에 그건 가능해. – stealthjong

관련 문제