0

我在标题中收到此错误。我从编辑文本字段创建 2 个数组列表并将它们保存在 xls 文件中。

保存:

File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
directory.mkdirs();            
File file = new File(directory, filename);


FileOutputStream fos;


try {
   fos = new FileOutputStream(file);
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
   bw.write(mydata+"\t"+myweight+"\n");
   bw.flush();
   bw.close();
    } catch (IOException e2) {
       e2.printStackTrace();
        }//catch

并加载:

       File sdCard = Environment.getExternalStorageDirectory();
        File directory = new File (sdCard, "MyFiles");
        File file = new File(directory, filename);

        String s;
        FileInputStream fis;

       try {
          fis = new FileInputStream(file);
             BufferedReader br = new BufferedReader(new InputStreamReader(fis));
             do {
                 s = br.readLine();
                 if (s != null)
                     {
                     data.add(Double.parseDouble(s));
                     weight.add(Double.parseDouble(s));
                     }
                 } while (s != null);
           } catch (IOException e) {
              e.printStackTrace();
               }
    }

它在“data.add(Double.parseDouble(s));”行中显示了数字格式异常。

另外,例如,我在 2 个字段 1,10 和 2,20 中输入,文件包含一个具有 [1.0, 2.0] [1.0, 2.0] 的单元格

其他数据?以及如何将数据放在 2 列中?

4

1 回答 1

1

保存数据的代码只存储一个包含两个数字的文本行,由制表符分隔。当您的代码读取文件时,您会读取整行,试图解析文本,这显然是不可解析的(有一个选项卡)。

您应该迭代编写每一行的数组。然后, read 方法应该拆分读取的字符串并分别解析每个子字符串。

问候。

让我们试着解释一下我会做什么[未编译]:

File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
directory.mkdirs();            
File file = new File(directory, filename);


FileOutputStream fos;

try {
    fos = new FileOutputStream(file);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
    //I assume mydata and myweight are both List<Double>... with same size
    for(int i = 0; i < mydata.size(); i++){
        bw.write(mydata.get(i)+"\t"+myweight.get(i)+"\n");
    }        
    bw.flush();
    bw.close();
} catch (IOException e2) {
    e2.printStackTrace();
}//catch

...

File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
File file = new File(directory, filename);

String s;
FileInputStream fis;

try {
    fis = new FileInputStream(file);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    do {
        s = br.readLine();
        if (s != null)
        {
            String[] splitLine = s.split("\\t");
            data.add(Double.parseDouble(splitLine[0]));
            weight.add(Double.parseDouble(splitLine[1]));
        }
    } while (s != null);
} catch (IOException e) {
     e.printStackTrace();
}
于 2013-04-15T21:43:46.897 回答