如何使用文本格式在sdcard中保存字符串数组?

时间:2012-07-18 08:35:05

标签: android byte fileoutputstream

  String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
        Log.d("list",TextUtils.join(",", values));
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);

              String a="hi  is";
                File myFile = new File("/sdcard/mysdcardfile.txt");
                try {
                    myFile.createNewFile();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    //byte[] anotherArray = new byte[values.length];
                    byte data[] = new byte[1024];
                    int count;
                    long total = 0;
                    FileOutputStream output = new FileOutputStream(myFile);
                    while ((count = values.length) != -1) {

                        total += count;
                //  FileWriter fos = new FileWriter(myFile);
               //   BufferedWriter bis = new BufferedWriter(fos);
                    output.write(data, 0, count);
                    //bis.close();
                    //fos.close();
                    output.close();
                    }   

这里我的值以文本格式存储在我的SD卡中。但是当我打开文本文件时,它包含bytes.here值存储在byte.how中,以便在我写fileoutputstrem时将字节更改为字符串。想要获取文本文件中的值。

3 个答案:

答案 0 :(得分:1)

如果要将其写为文本,请不要使用DataOutputStream。 Streams(InputStream和OutputStream)用于读取和写入二进制数据,而不是文本。如果您要撰写文字,请使用Writer代替OutputStream。例如:

String[] array = ...  // wherever you get this from;  

File file = new File("StringFile.txt");  
PrintWriter out = new PrintWriter(new FileWriter(file));  

// Write each string in the array on a separate line  
for (String s : array) {  
    out.println(s);  
}  


out.close();  

别忘了把

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

在应用程序的清单文件中。

答案 1 :(得分:0)

读取字节数组中的文件并将其转换为String,如下所示。

    byte[] array = new byte[1000]; // 1000 is just given u can change it accordingly
      String s= new String(array);

答案 2 :(得分:0)

为什么不使用SQLite数据库或ContentProvider?

您可以使用DataOutputStream.writeUTF()和DataInputStream.readUTF(),因为这些方法会将字符串的长度放在文件中并自动读回正确数量的字符。