2015-03-25 40 views
1

我正在android中創建一個基於模式鎖定的項目。 我有一個名爲category.txt 文件的文件的內容如下在java前面追加一個字符串?

Sports:Race:Arcade:

沒有我想要的是,每當用戶繪製的圖案爲一個特定的遊戲類的模式應該在前面得到追加該類別。

例如: Sports:Race:"string/pattern string to be appended here for race"Arcade: 我已經使用下面的代碼,但它不工作。

private void writefile(String getpattern,String category) 
{ 

    String str1; 
    try { 
     file = new RandomAccessFile(filewrite, "rw"); 

     while((str1 = file.readLine()) != null) 
     { 
      String line[] = str1.split(":"); 
      if(line[0].toLowerCase().equals(category.toLowerCase())) 
      { 
       String colon=":"; 
       file.write(category.getBytes()); 
       file.write(colon.getBytes()); 
       file.write(getpattern.getBytes()); 
       file.close(); 
       Toast.makeText(getActivity(),"In Writefile",Toast.LENGTH_LONG).show(); 
      } 
     } 

    } 
    catch (FileNotFoundException e) 
    { 
     e.printStackTrace(); 
    } 
    catch(IOException io) 
    { 
     io.printStackTrace(); 
    } 


} 

請大家幫忙!

+0

究竟什麼是行不通的?我試了一下,發現問題是雖然文件關閉(s。'file.close()'調用),循環繼續。這會導致IOException。 – Ria 2015-03-25 09:40:38

+0

我不知道爲什麼它不適合我。 你能否給我提供一些可以讀取文件的附加字符串,例如在Race的前面加上「any string」:「要附加的字符串」。 – 2015-03-26 04:14:48

+0

爲了確保我正確理解了這一點:你的文件只包含一行,如'Sports:Race:Arcade:'。如果給定的類別與字符串中的元素相匹配(比如'Race'),您想要將提供的模式追加到類別前並將其寫回到同一個文件中? – Ria 2015-03-26 07:00:51

回答

0

使用RandomAccessFile您必須計算位置。我認爲用apache-commons-io FileUtils來替換文件內容要容易得多。如果你有一個非常大的文件,這可能不是最好的想法,但它很簡單。

String givenCategory = "Sports"; 
    String pattern = "stringToAppend"; 
    final String colon = ":"; 
    try { 
     List<String> lines = FileUtils.readLines(new File("someFile.txt")); 
     String modifiedLine = null; 
     int index = 0; 
     for (String line : lines) { 
      String[] categoryFromLine = line.split(colon); 
      if (givenCategory.equalsIgnoreCase(categoryFromLine[0])) { 
       modifiedLine = new StringBuilder().append(pattern).append(colon).append(givenCategory).append(colon).toString(); 
       break; 
      } 
      index++; 
     } 
     if (modifiedLine != null) { 
      lines.set(index, modifiedLine); 
      FileUtils.writeLines(new File("someFile.txt"), lines); 
     } 

    } catch (IOException e1) { 
     // do something 
    }