Example usage for java.io File getTotalSpace

List of usage examples for java.io File getTotalSpace

Introduction

In this page you can find the example usage for java.io File getTotalSpace.

Prototype

public long getTotalSpace() 

Source Link

Document

Returns the size of the partition named by this abstract pathname.

Usage

From source file:me.kartikarora.transfersh.activities.TransferActivity.java

private void uploadFile(Uri uri) throws IOException {
    final ProgressDialog dialog = new ProgressDialog(TransferActivity.this);
    dialog.setMessage(getString(R.string.uploading_file));
    dialog.setCancelable(false);//from w  w w.j  av a  2 s .  co m
    dialog.show();
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        final String name = cursor.getString(nameIndex);
        final String mimeType = getContentResolver().getType(uri);
        Log.d(this.getClass().getSimpleName(), cursor.getString(0));
        Log.d(this.getClass().getSimpleName(), name);
        Log.d(this.getClass().getSimpleName(), mimeType);
        InputStream inputStream = getContentResolver().openInputStream(uri);
        OutputStream outputStream = openFileOutput(name, MODE_PRIVATE);
        if (inputStream != null) {
            IOUtils.copy(inputStream, outputStream);
            final File file = new File(getFilesDir(), name);
            TypedFile typedFile = new TypedFile(mimeType, file);
            TransferClient.getInterface().uploadFile(typedFile, name, new ResponseCallback() {
                @Override
                public void success(Response response) {
                    BufferedReader reader;
                    StringBuilder sb = new StringBuilder();
                    try {
                        reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
                        String line;
                        try {
                            while ((line = reader.readLine()) != null) {
                                sb.append(line);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String result = sb.toString();
                    Snackbar.make(mCoordinatorLayout, name + " " + getString(R.string.uploaded),
                            Snackbar.LENGTH_SHORT).show();

                    ContentValues values = new ContentValues();
                    values.put(FilesContract.FilesEntry.COLUMN_NAME, name);
                    values.put(FilesContract.FilesEntry.COLUMN_TYPE, mimeType);
                    values.put(FilesContract.FilesEntry.COLUMN_URL, result);
                    values.put(FilesContract.FilesEntry.COLUMN_SIZE, String.valueOf(file.getTotalSpace()));
                    getContentResolver().insert(FilesContract.BASE_CONTENT_URI, values);
                    getSupportLoaderManager().restartLoader(BuildConfig.VERSION_CODE, null,
                            TransferActivity.this);
                    FileUtils.deleteQuietly(file);
                    if (dialog.isShowing())
                        dialog.hide();
                }

                @Override
                public void failure(RetrofitError error) {
                    error.printStackTrace();
                    if (dialog.isShowing())
                        dialog.hide();
                    Snackbar.make(mCoordinatorLayout, R.string.something_went_wrong, Snackbar.LENGTH_INDEFINITE)
                            .setAction(R.string.report, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    // TODO add feedback code
                                }
                            }).show();
                }
            });
        } else
            Snackbar.make(mCoordinatorLayout, R.string.unable_to_read, Snackbar.LENGTH_SHORT).show();
    }
}

From source file:com.arkami.myidkey.activity.KeyCardEditActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if ((resultCode == RESULT_OK)) {

        ///*ww  w  . ja  v  a2 s . c o m*/

        File file = null;
        FileObject fileObject = new FileObject();
        fileObject.setKeyCardAttribute(true);

        if ((requestCode == CHOOSE_IMAGE_ACTIVITY_REQUEST_CODE)
                || (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)) {

            //
            File image;
            try {
                image = new File(getImageUrlFromResult(data));
                // copy file
                File destination = new File(
                        KeyCardEditActivity.this.getFilesDir() + getString(R.string.key_cards_files_folder));
                String copyToFileName = destination.getPath() + "/" + image.getName();

                FileChooserActivity.copyFiles(image, destination, KeyCardEditActivity.this);
                image = new File(copyToFileName);
            } catch (IllegalArgumentException ex) {
                Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
                ex.printStackTrace();
                return;
            }
            fileObject.setFileType(1L);
            fileObject.setKeyCardAttribute(true);
            fileObject.setName(image.getName());
            fileObject.setPathToFile(image.getPath());
            fileObject.setSize(image.getTotalSpace());
            fileObject.setCreateDate(new Date().getTime());
            fileObject.setModifyDate(new Date().getTime());
            addFileToList(fileObject);
            return;
            // File file = null;
            // FileObject fileObject = new FileObject();
            // fileObject.setKeyCardAttribute(true);
            // if ((requestCode == CHOOSE_IMAGE_ACTIVITY_REQUEST_CODE)
            // || (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)) {
            // fileObject.setFileType(Cache.getInstance(this).getFileTypeId(
            // FileTypeEnum.photo));
            // String selectedImageUrl;
            // if (data == null) {
            // selectedImageUrl = photoUri.getPath();
            // } else {
            // String[] filePathColumn = {MediaColumns.DATA};
            // Cursor cursor = getContentResolver().query(data.getData(),
            // filePathColumn, null, null, null);
            // cursor.moveToFirst();
            // int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            // selectedImageUrl = cursor.getString(columnIndex);
            // cursor.close();
            // }
            // if (selectedImageUrl == null) {
            // return;
            // }
            //
            //
            // if ((selectedImageUrl != null)) {
            // file = new File(selectedImageUrl);
            // if ((file != null) && (file.exists()) && (file.isFile())
            // && (file.canRead())) {
            // // try {
            // // Common.copyFileToAppFolder(file, this);
            // // move to receiving message
            // fileObject.setCreateDate(new Date().getTime());
            // fileObject.setModifyDate(new Date().getTime());
            // fileObject.setName(file.getName());
            // fileObject.setPathToFile( file.getPath());
            // //fileObject.setPathToFile("/myAppFolder/" + file.getName());
            // fileObject.setSize(file.length());
            // fileObject.setId(fileDataSource.insert(fileObject));
            // //
            // // } catch (IOException e) {
            // // e.printStackTrace();
            // // }
            //
            // } else{
            // Log.w("key card File is null", (file == null) + "");
            // Log.w("key card File is existing", file.exists() + "");
            // Log.w("key card File is file",file.isFile() + "");
            // Log.w("key card File is readable", file.canRead() + "");
            // }
            // }
        }

        if ((requestCode == CHOOSE_AUDIO_ACTIVITY_REQUEST_CODE)
                || (requestCode == CAPTURE_AUDIO_ACTIVITY_REQUEST_CODE)) {

            fileObject.setFileType(Cache.getInstance(this).getFileTypeId(FileTypeEnum.audio));
            Uri selectedAudio = null;
            if (data != null) {
                selectedAudio = data.getData();
            }

            String[] filePathColumn = { MediaStore.Audio.Media.DATA };
            if ((selectedAudio != null) && (filePathColumn != null)) {

                Cursor cursor = getContentResolver().query(selectedAudio, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);
                cursor.close();
                file = new File(filePath);

                File destination = new File(
                        KeyCardEditActivity.this.getFilesDir() + getString(R.string.key_cards_files_folder));
                String copyToFileName = destination.getPath() + "/" + file.getName();

                FileChooserActivity.copyFiles(file, destination, KeyCardEditActivity.this);
                file = new File(copyToFileName);

                fileObject.setCreateDate(new Date().getTime());
                fileObject.setModifyDate(new Date().getTime());
                fileObject.setName(file.getName());
                fileObject.setPathToFile(file.getPath());
                fileObject.setSize(file.length());
                fileObject.setKeyCardAttribute(true);
                fileObject.setId(fileDataSource.insert(fileObject));
                // appAudios.add(file);
            }
        }
        // addFileToList(fileObject);

        // try {
        // Common.copyFileToAppFolder(audio, this);
        // XXX duplicate code
        long[] newIds = Arrays.copyOf(keyCard.getFileIds(), keyCard.getFileIds().length + 1);
        long newId = fileObject.getId();
        newIds[newIds.length - 1] = newId;
        Toast.makeText(this, newId + "", Toast.LENGTH_SHORT).show();
        keyCard.setFileIds(newIds);
        // keyCardDataSource.update(keyCard);
        Log.w("file ", "added");
    }
    Toast.makeText(this, "no file", Toast.LENGTH_LONG).show();

    // super.onActivityResult(requestCode, resultCode, data);
}

From source file:com.bibisco.test.ProjectManagerTest.java

@Test
public void testExportProjectAsArchive() {

    ContextManager.getInstance().setIdProject(AllTests.TEST_PROJECT_ID);
    File lFile = ProjectManager.exportProjectAsArchive();
    Assert.assertNotNull(lFile);//from  w  w w  .j av  a  2  s  .  c o m
    Assert.assertEquals("C:\\Users\\afeccomandi\\git\\bibisco\\bibisco\\export", lFile.getParent());
    Assert.assertTrue(lFile.getName().startsWith("Test_archive"));
    Assert.assertTrue(lFile.getName().endsWith(".bibisco"));
    Assert.assertTrue(lFile.getTotalSpace() > 0);

    ContextManager.getInstance().setIdProject(AllTests.TEST_PROJECT2_ID);
    lFile = ProjectManager.exportProjectAsArchive();
    Assert.assertNotNull(lFile);
    Assert.assertEquals("C:\\Users\\afeccomandi\\git\\bibisco\\bibisco\\export", lFile.getParent());
    Assert.assertTrue(lFile.getName().startsWith("Test2_archive"));
    Assert.assertTrue(lFile.getName().endsWith(".bibisco"));
    Assert.assertTrue(lFile.getTotalSpace() > 0);

    ContextManager.getInstance().setIdProject(AllTests.TEST_PROJECT3_ID);
    lFile = ProjectManager.exportProjectAsArchive();
    Assert.assertNotNull(lFile);
    Assert.assertEquals("C:\\Users\\afeccomandi\\git\\bibisco\\bibisco\\export", lFile.getParent());
    Assert.assertTrue(lFile.getName().startsWith("Test3_archive"));
    Assert.assertTrue(lFile.getName().endsWith(".bibisco"));
    Assert.assertTrue(lFile.getTotalSpace() > 0);
}

From source file:com.ebay.erl.mobius.core.collection.BigTupleList.java

/**
 * Flush {@link Tuple}s in {@link #buffer_in_memory} into
 * disk, and new local file will be created by {@link #newLocalFile()}
 * and store the {@link File} reference in {@link #buffer_on_disk} for
 * future reference.//w  ww  .j av  a 2  s . c om
 */
private void flushToDisk() {
    this.flushing = true;
    File localFile;

    if (this.buffer_in_memory.size() == 0) {
        // no tuple in memory
        return;
    }
    long start = System.currentTimeMillis();
    long availableMemory = this.availableMemory();

    String message = Thread.currentThread().toString() + " BID[" + this._ID + "] "
            + "writing in-memory tuples (" + getNumberFormat().format(this.buffer_in_memory.size())
            + " entries) into disk, " + "available memory:" + availableMemory / _MB + "MB.";

    LOGGER.info(message);
    if (this.reporter != null) {
        this.reporter.setStatus(message);
        this.reporter.progress();
    }

    try {
        // check if we still have enough local space to prevent 
        // full of disk exception.
        long freeDiskSpace = this.workOutput.getFreeSpace() / _MB;
        if (freeDiskSpace < 300) {
            // less than 300MB free space left, throw
            // exceptions
            throw new IOException("Not enough space left (" + freeDiskSpace + "MB remaining) on "
                    + this.workOutput.getAbsolutePath() + ".");
        }

        localFile = this.newLocalFile();
        DataOutputStream out = new DataOutputStream(
                new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(localFile))));

        // write the tuple schema in the header
        String[] tupleSchema = this.buffer_in_memory.get(0).getSchema();
        out.writeInt(tupleSchema.length);
        if (tupleSchema.length == 0)
            throw new IllegalArgumentException("Tuple with empty schema!");
        for (String aColumn : tupleSchema) {
            out.writeUTF(aColumn);
        }

        // write number of tuple in this file
        out.writeLong(this.buffer_in_memory.size());

        if (this.comparator != null) {
            // sort the Tuple in memory first
            Collections.sort(this.buffer_in_memory, this.comparator);
        }

        // write all the tuple in memory buffer
        long counts = 0L;
        for (Tuple aTuple : this.buffer_in_memory) {
            aTuple.write(out);
            counts++;
            if (counts % 5000 == 0 && this.reporter != null)// report every 5000 IO
                this.reporter.progress();
        }
        out.flush();
        out.close();

        // clear memory buffer
        this.buffer_in_memory.clear();

        long end = System.currentTimeMillis();

        LOGGER.info(Thread.currentThread().toString() + " BID[" + this._ID + "] " + "Write has completed, cost "
                + ((end - start) / 1000) + " seconds, " + "available memory:" + this.availableMemory() / _MB
                + "MB, " + "wrote to:" + localFile.getAbsolutePath() + "(size:"
                + localFile.getTotalSpace() / _MB + "MB) , " + "in memory tuples numbers:"
                + this.buffer_in_memory.size());

        this.flushing = false;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}