0

I need to convert this File object to byte array:

File directory=new File(Environment.getExternalStorageDirectory() + "");

(I need only the names of folders and files on SDcard.)

I have already tried this:

 byte[] send=null;
            FileInputStream fis;
            try {
                fis = new FileInputStream(directory);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int readBytes = 0;
            while(readBytes != -1)
            {

                    readBytes = fis.read(buffer);

                if(readBytes > 0)
                {
                    bos.write(buffer, 0, readBytes);
                }
                else 
                    break;
            }
            byte[] fileData = bos.toByteArray();
            send=fileData;

But it returns this error: java.io.FileNotFoundException: /mnt/sdcard (Is a directory)

  • File implements serializable, so perhaps http://stackoverflow.com/questions/2836646/java-serializable-object-to-byte-array might help. – fladrif Sep 20 '12 at 21:49

1 Answers1

1

You're trying to load the directory as if it were a file. It's not. What would you expect the contents of the byte array to be?

If you want to find the list of files in a directory, use File.listFiles().

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I wanna make remote file explorer. And I need to get this File object as it is to another phone via bluetooth (and I able to send only byte arrays). Sorry for my english – user1681497 Sep 20 '12 at 21:30
  • @user1681497: The `File` really only knows the path. If you're trying to get the names of the files and folders within it, you'll need to use `File.listFiles()` (or just `File.list()` for strings.) – Jon Skeet Sep 20 '12 at 21:33
  • Oh, ok... So I have to send the File.list() from one phone to another everytime, when the user opens a folder :( – user1681497 Sep 20 '12 at 21:39
  • @user1681497: Well you *could* basically send the entire file system, in your own custom format - that does sound like a good idea to me though. Perhaps send the full structure in terms of file names as a recursive tree structure, and have a separate call to get file contents. – Jon Skeet Sep 20 '12 at 21:40