Android openFileInput无法解析文件路径

时间:2015-04-21 09:18:36

标签: java android fileinputstream

我添加了外部库以进行文件浏览。该库返回选定的文件路径键,但不返回值。

package com.example.dev.nordugrid;
import com.orleonsoft.android.simplefilechooser.ui.FileChooserActivity;

import android.content.Context;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;
import android.view.View;
import android.content.Intent;
import java.io.*;

public class jdlFailas extends ActionBarActivity {
final int FILE_CHOOSER = 1;
public String fileSelected;
public String myText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_jdl_failas);
}

public void openFILE(View view) {
    Intent intent = new Intent(jdlFailas.this, FileChooserActivity.class);
    startActivityForResult(intent, FILE_CHOOSER);

    try {
        FileInputStream fin = new FileInputStream ( fileSelected);
        int c;
        String temp="";
        while( (c = fin.read()) != -1){
            temp = temp + Character.toString((char)c);
        }

        fin.close();
        myText = temp.toString();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
    }
}


public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ((requestCode == FILE_CHOOSER) && (resultCode == RESULT_OK)) {
        fileSelected = data.getStringExtra(com.orleonsoft.android.simplefilechooser.Constants.KEY_FILE_SELECTED);

        TextView textView = (TextView) findViewById(R.id.editText2);

        Toast.makeText(this, R.string.pasirinktasFailas + myText, Toast.LENGTH_SHORT).show();
        textView.setText(myText);
    }
}

public void jdlSave(View view) {
    Intent intent = new Intent(jdlFailas.this, NaujaUzduotis.class);
    startActivity(intent);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_jdl_failas, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

如果我输入普通文件名,程序运行正常:

   FileInputStream fin = openFileInput("file.txt");

无论如何,我的主要问题是"如果我想使用路径而不是字符串,我如何处理文件?"

.xml文件

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.dev.nordugrid.jdlFailas">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="@string/pridekiteJDL"
    android:id="@+id/textView6"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/prideti"
    android:id="@+id/button12"
    android:onClick="openFILE"
    android:layout_below="@+id/textView6"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="@string/rasytiRanka"
    android:id="@+id/textView7"
    android:layout_below="@+id/button12"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textMultiLine"
    android:ems="10"
    android:id="@+id/editText2"
    android:layout_below="@+id/textView7"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/ikelti"
    android:id="@+id/button13"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:onClick="jdlSave" />

在pastebin链接中有LogCat代码:http://pastebin.com/43kzEgRu

4 个答案:

答案 0 :(得分:3)

你的问题最终是由于忽视了

之间的关键区别
FileInputStream fin = openFileInput("file.txt");

VS

FileInputStream fin = new FileInputStream("failas.txt")

第一个是可行的(在活动或服务中),因为openFileInput()是Android独有的方法,可以打开位于应用程序私人目录中的文件

第二个是Android上不可行,因为Java的FileInputStream(String path)构造函数只给出一个文件名时会尝试在工作目录中打开一个文件,在Android上就是设备的根目录 - 您的应用无法存储任何数据的地方。

当您使用“/storage/sdcard/uzduotis.txt”表示的路径处理外部存储时,您无法使用openFileInput(),但与您的断言相比,可以执行以下操作:

String path = "/storage/sdcard/uzduotis.txt";
FileInputStream fin = new FileInputStream(path);

甚至可以将其硬编码为

FileInputStream fin = new FileInputStream("/storage/sdcard/uzduotis.txt");

当然,总体而言,总体而言,取决于所有常见情况,例如拥有工作程序,拥有外部存储权限,以及之前在该名称和位置创建了文件。

答案 1 :(得分:2)

当file_name包含路径时,我遇到了类似的问题:

InputStream inputStream = context.openFileInput(file_name);

解决方案是用以下内容替换上面的行:

file_name=context.getFilesDir() + "/"+file_name;
InputStream inputStream = new FileInputStream(new File(file_name));

答案 2 :(得分:0)

public void openFILE(View view) {
Intent intent = new Intent(jdlFailas.this, FileChooserActivity.class);
startActivityForResult(intent, FILE_CHOOSER);

try {
    FileInputStream fin = new FileInputStream ( fileSelected);
    int c;
    String temp="";
    while( (c = fin.read()) != -1){
        temp = temp + Character.toString((char)c);
    }

    fin.close();
    myText = temp.toString();

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
}
}

如前所述:由于用户首先必须选择文件,因此无法立即打开文件。所以改为:

public void openFILE(View view) {
Intent intent = new Intent(jdlFailas.this, FileChooserActivity.class);
startActivityForResult(intent, FILE_CHOOSER);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == FILE_CHOOSER) && (resultCode == RESULT_OK)) {
    fileSelected = data.getStringExtra(com.orleonsoft.android.simplefilechooser.Constants.KEY_FILE_SELECTED);
    Toast.makeText(this, fileSelected, Toast.LENGTH_SHORT).show();

try {
    FileInputStream fin = new FileInputStream ( fileSelected);
    int c;
    String temp="";
    while( (c = fin.read()) != -1){
        temp = temp + Character.toString((char)c);
    }

    fin.close();
    myText = temp.toString();
    TextView textView = (TextView) findViewById(R.id.editText2);

    Toast.makeText(this, R.string.pasirinktasFailas + myText, Toast.LENGTH_SHORT).show();
    textView.setText(myText);
} catch (FileNotFoundException e) {
    e.printStackTrace();
    Toast.makeText(this, "FileNotFoundException: " + e.getMessage(), Toast.LENGTH_SHORT).show();
  } catch (IOException e) {
 e.printStackTrace();       
  Toast.makeText(this, "IOException: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}

答案 3 :(得分:0)

如果您拥有一部手机,那么您将从路径下方获取 openFileInput()

#include <iostream>
#include <vector>
#include <cstdarg>

class matrix{
    public:
        matrix(){};
        matrix(std::initializer_list<std::vector<int>> vectors):x(vectors){}
        ~matrix(){};

        const int& size(){ return this->x.size(); } //# of vectors
        //ALT: ex. print: 3x3, 4x5, 7x3
        //void size(){ std::cout<<"Dim: "<<this->x.size<<"x"<<this->x.front().size()<<std::endl;
        void add(const std::vector<int>& arr){ this->x.push_back(arr); }
        const std::vector<std::vector<int>>& extract(){ return this->x; } //Returns entire matrix
        const std::vector<int>& getVector(const int& row){ return this->x.at(row); } //Returns specific vector from matrix

        matrix operator*(const matrix& m){ //More params
            //Stuff here
        }
        matrix operator*=(const matrix& m){ //More params
            //Stuff here
        }

    private:
        std::vector<std::vector<int>> x;
};

//Can break the center out to make one for vectors too
std::ostream& operator<<(std::ostream& os, matrix& m){
    for (auto& it:m.extract()){
        for (auto& jt:it){
            os<<jt<<" ";
        }
        os<<std::endl;
    }
    os<<std::endl;
    return os;
}


int main(){
    matrix m({{2,5,8,11,14},
              {3,6,9,12,15},
              {4,7,10,13,16}});
    std::cout<<m;

    return 0;
}

使用相同路径的设备文件浏览器进行其他明智的检查