开发者

how to write SimpleDateFormat fo file in Android

I'm new in Andy world. I'm doing mine first app. GPS tracker. I need to save coordinates + (time ,date) to file on SD.

Coordinates are easy, but Time & Date ( in SimpleDateFormat) make me a trouble.

write() method has problem with SDF. I've tried c开发者_JAVA百科onvert to string and many other things.

official error message is: "The method write(byte[]) in the type FileOutputStream is not applicable for the arguments (String)"

  FileOutputStream fos = openFileOutput("kris.txt", Context.MODE_PRIVATE);
    SimpleDateFormat sdf = new SimpleDateFormat( "yyyy/MM/dd' 'HH:mm:ss " ); 
    String k = sdf.toString();
    fos.write(k);
    fos.flush();
    fos.close();


As I understood you just need to change the method. To write strings to a file you need to use BufferedWrite or PrintWriter.

Try this:

public void writeLinesToFile(String filename,
                               String[] linesToWrite,
                               boolean appendToFile) {
    PrintWriter pw = null;
    try {
      if (appendToFile) {
        //If the file already exists, start writing at the end of it.
        pw = new PrintWriter(new FileWriter(filename, true));
      }
      else {
        pw = new PrintWriter(new FileWriter(filename));
      }
      for (int i = 0; i < linesToWrite.length; i++) {
        pw.println(linesToWrite[i]);
      }
      pw.flush();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {
      //Close the PrintWriter
      if (pw != null)
        pw.close();
    }
  }

(code from a java manual)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜