2013-07-15 38 views
0

longlat文件:保存的ArrayList <String>到文本文件

101.2425101.2334103.345 

编码具有算法是这样的:

ArrayList<String> getDifferenceList(String filePath) { 
    File f = new File("longlat.txt"); 

    String line, x1 = null, x2= null, x3 = null; 

BufferedReader buffreader = null; 

try { 
    buffreader = new BufferedReader(new FileReader(f)); 
    while ((line = buffreader.readLine()) != null) { 
     String[] parts = line.split(""); 
     x1 = (parts[0]); 
     x2 = (parts[1]); 
     x3 = (parts[2]); 
    } 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

ArrayList<String> ret = new ArrayList<String>(); 
FileWriter writer; 




if (x1 == null || x1.isEmpty() 
     || x2 == null || x2.isEmpty() 
     || x3 == null || x3.isEmpty()) { 

    ret.add(x1); 
    ret.add(x2); 
    ret.add(x3); 

    return ret; 
} 

int index = 0; 

while (index < x1.length() 
     && index < x2.length() 
     && index < x3.length()) { 
    if (x1.charAt(index) != x2.charAt(index) 
      || x1.charAt(index) != x3.charAt(index)) { 
     break; 
    } 
    index++; 
} 

ret.add(x1.substring(index, x1.length())); 
ret.add(x2.substring(index, x2.length())); 
ret.add(x3.substring(index, x3.length())); 


return ret; 


} 

的值需要被保存到文本文件中的数组列表中ret。

我已经试过:

FileWriter writer = new FileWriter("lalala.txt"); 
    for(String str: ret) { 
     writer.write(str);   
     } writer.close(); 

我把上面的编码在顶部:

ret.add(x1.substring(index, x1.length())); 

问题:当我点击一个按钮,显示没有“显示LALALA文本”。

和还试图

try { 
     OutputStreamWriter out = new OutputStreamWriter(openFileOutput ("lalala.txt",MODE_APPEND));  
       String text =(ret); 
       out.write(text); 
       out.write('\n');    
       out.close(); 
        } 
     catch (java.io.IOException e) { 
     Toast.makeText(this,"Sorry Text could't be added",Toast.LENGTH_LONG).show 
();} 
            } 

我把上述编码处的顶部:

ret.add(x1.substring(index, x1.length())); 

问题:错误在 '保留'。它说:“类型不匹配:不能从ArrayList转换为字符串”

我不知道如何将数组列表存储到文本文件中。 请给我一些想法,谢谢。

+0

可以请出示文件longlat.txt为您的时间 – veritas

+0

@veritas我已经更新,谢谢?我试过这个,但是当我点击一个按钮来查看lalala.txt时,这不会显示任何内容。我的方法是否有权调用“longlat.txt”? @kocko – doraemon

回答

1

ArrayList<String>不能转换为String

你可以写ArrayList到一个文件中这样的内容:写你的数组列表RET

I put the above coding at the top of : 
ret.add(x1.substring(index, x1.length())); 

你退役之前,你正在写文件

PrintWriter out = null; 
try { 
    out = new PrintWriter(new FileWriter("lalala.txt")); 
    for (String text : ret) { 
     out.writeln(text); 
    }    
} catch (IOException e) { 
    System.err.println("Caught IOException: " + e.getMessage()); 

} finally { 
    if (out != null) { 
     out.close(); 
    } 
} 
+0

,我需要把这个编码内容 – doraemon

+1

不完全正确的把正确的。而不是写它是println。 – Alexey

0

是在此之前空线。你的if条件评估真实,然后它实际上从那里返回。 if-condition评估为false。那么你有空的数组列表。

有完全填充你的arrayList后写入文件。

即就在返回语句之前。

return ret; 
+0

仍然没有显示任何东西 – doraemon