2013-06-04 150 views
0

在下面提到的代碼中,我將虛擬內容寫入名爲「testfile.txt」的文件中。但我想在外部存儲的任何文件中編寫虛擬內容。我不希望文件名被硬編碼。我該怎麼做?在外部存儲的文件中寫入虛擬內容android

String root = android.os.Environment.getExternalStorageDirectory().getPath(); 
File myFile = new File(root,"testfile.txt"); 

FileChannel rwChannel = new RandomAccessFile(myFile, "rw").getChannel(); 
int numBytes = (int)rwChannel.size(); 
ByteBuffer buffer = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, numBytes); 
System.out.println("buffer"+buffer); 
byte[] randomBytes = new byte[numBytes]; 
new Random().nextBytes(randomBytes); 
buffer.put(randomBytes); 
rwChannel.write(buffer); 
rwChannel.close(); 

回答

0
File root = android.os.Environment.getExternalStorageDirectory(); 
File[] files = root.listFiles(); 
for (File f : files) { 
    if (f.isDirectory()) 
     continue; 
    //write here 
} 
+0

我收到錯誤的RandomAccessFile作爲,改變類型的文件到文件。 File [] files = root.listFiles();對於(文件f:文件){if(f.isDirectory()) \t繼續; FileChannel rwChannel = new RandomAccessFile(files,「rw」)。getChannel(); – user2435558

相關問題