0

我正在尝试将一个空的临时文本文件上传到谷歌驱动器,但它没有成功。file返回 null。但是,我可以使用 google drive 网站上的示例从我的相机上传图像。我需要为缓存设置任何特殊权限吗?谢谢你的帮助。

这是我的尝试:

java.io.File outputDir = getApplicationContext().getCacheDir(); // context being the Activity pointer
java.io.File tempFile = java.io.File.createTempFile("hello", "txt", outputDir);
FileContent mediaContent = new FileContent("text/plain", tempFile);

// File's metadata.
File body = new File();
body.setTitle(tempFile.getName());
body.setMimeType("text/plain");
File file = service.files().insert(body, mediaContent).execute();

谷歌示例是如何做到的:

String mediaStorageDir = Environment.getExternalStoragePublicDirectory(
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
fileUri = Uri.fromFile(new java.io.File(mediaStorageDir + java.io.File.separator + "IMG_"
+ timeStamp + ".jpg"));

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
saveFileToDrive();


private void saveFileToDrive() {
  Thread t = new Thread(new Runnable() {
  @Override
 public void run() {
    try {           
        java.io.File fileContent = new java.io.File(fileUri.getPath());
        FileContent mediaContent = new FileContent("image/jpeg", fileContent);

        // File's metadata.
        File body = new File();
        body.setTitle(fileContent.getName());
        body.setMimeType("image/jpeg");
        File file = service.files().insert(body, mediaContent).execute();
    }
 });}
4

1 回答 1

0

greenapps 回答了它。我无法上传空文本文件。我想我可以,因为您可以上传带有正文(标题、mime 类型..)但没有任何内容的文件。

我的代码最终成为

            java.io.File tempFile = java.io.File.createTempFile("supertime", "txt");

            String tempPath = tempFile.getAbsolutePath();

            BufferedWriter bw = new BufferedWriter(new FileWriter(tempPath));
            bw.write("Hello");
            bw.close();

            FileContent mediaContent = new FileContent("text/plain", tempFile);
            Log.i("Drive", tempPath);
            FileInputStream fis = new FileInputStream(tempPath);

            StringBuilder sb = inputStreamToStringBuilder(fis);
            showText(sb);
            Log.i("Drive", "done input stream");
            // File's metadata.
            File body = new File();
            body.setTitle("Kapleck");
            body.setMimeType("text/plain");
            File file = service.files().insert(body, mediaContent).execute();
于 2013-04-03T18:29:38.553 回答