开发者

How to set file length zero in Android?

I want to set file length to zero. i used following code

      try 
      {
          new RandomAccessFile(file,"rw").setLength(0);
      } 
      开发者_JAVA技巧catch (FileNotFoundException e1) 
      {
          // TODO Auto-generated catch block
          Log.i("Exception caught ==> ", e1.toString());
          e1.printStackTrace();
      } 
      catch (IOException e) 
      {
          // TODO Auto-generated catch block
          Log.i("Exception caught ==> ", e.toString());
          e.printStackTrace();
      }

The problem, if again anything i write in the file means, it showing some speacial character in the file like AAAAAAAAAAAA and followed my content. Please give me some suggestion.


The issue may be in read buffer. if you have want to read a file which has 10 bytes data and you have created a byte[] of 15 then you wil get extra null there. better create a byte array of size same as file length. also after getting string you can trim() the data

I have tried with the following code but didnot get any issue.

Sample Code

RandomAccessFile ram = null;
    byte[] mydata = null;
    try 
    {
        System.out.println("...rrunning my app...");
        String str =Environment.getExternalStorageDirectory().getAbsolutePath()+"/myfile.txt";
//      File f = new File(str);
        ram =new RandomAccessFile(str,"rw");
        ram.setLength(0);
        ram.write("i am fine".getBytes());
        System.out.println("...file length..."+ram.length());
        mydata = new byte[(int) ram.length()];
        ram.close();
        RandomAccessFile ram1 =new RandomAccessFile(str,"rw");
        ram1.read(mydata);
        System.out.println("...data present in 11file..."+new String(mydata));

    } 
    catch (Exception e1) 
    {
        // TODO Auto-generated catch block
        Log.i("Exception caught ==> ", e1.toString());
        e1.printStackTrace();
    } 


with

try (FileOutputStream fos = new FileOutputStream("xxx")) {
    fos.write(new byte[0]);
}

or also

try (FileWriter fw = new FileWriter("xxx")) {
    fw.write("");
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜