使用文件输入流找不到文件异常

Ben*_*rce 1 java android file-upload filenotfoundexception filepath

我正在尝试使用下面的代码将文件从硬盘加载到文件输入流.

package com.filefinder1;

import java.io.File;
import java.io.FileInputStream;
import android.app.Activity;
import android.os.Bundle;

public class FileFinder_1Activity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try
        {
        String pathToFile = "C:\\\\Koala_Small.jpg";
        System.out.println("File Path: "+pathToFile);
        File file = new File(pathToFile);
         FileInputStream fileInputStream = new FileInputStream(file);
    }
    catch (Exception ex)
    {
    System.out.println("Error Catch Triggered: "+ex);
    }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在文件路径上尝试了一些不同的变体,但没有任何东西都返回以下错误:

01-10 10:59:06.189: I/System.out(2218): Error Catch Triggered: java.io.FileNotFoundException: /C:\\Koala_Small.jpg (No such file or directory)
Run Code Online (Sandbox Code Playgroud)

一些额外的"/"似乎被添加到文件路径(不知道为什么).当我要求系统在尝试将其加载到文件变量之前打印文件路径时,它返回:

01-10 10:59:06.189: I/System.out(2218): File Path: C:\\Koala_Small.jpg
Run Code Online (Sandbox Code Playgroud)

我尝试了一堆不同的文件路径变体(小写"c",两个斜线而不是四个...)似乎没有什么可以解决这个问题.有没有人知道这里可能出了什么问题?

rog*_*oom 5

您应该将该文件放在android项目的assets目录中.

然后从您的活动中执行以下操作:

getAssets().open("Koala_Small.jpg");
Run Code Online (Sandbox Code Playgroud)

这将返回您的输入流.

正如评论中提到的那样,模拟器无法以您尝试的方式访问您的pc文件系统.