Android 将文件保存在内部存储器中

Android 将文件保存在内部存储器中,android,local-storage,mkdirs,Android,Local Storage,Mkdirs,我是android新手,在尝试将文件保存到内部存储时遇到了问题,新的示例适用于我的sdk,但不适用于我的手机 我正试图在索尼爱立信xperia上运行de示例,顺便说一下,android 2.1。。。log.i-给了我下一行: /data/data/com.example.key/files/text/(my_title) 谢谢 @Override protected void onCreate(Bundle savedInstanceState) {

我是android新手,在尝试将文件保存到内部存储时遇到了问题,新的示例适用于我的sdk,但不适用于我的手机

我正试图在索尼爱立信xperia上运行de示例,顺便说一下,android 2.1。。。log.i-给了我下一行:

/data/data/com.example.key/files/text/(my_title) 
谢谢

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);

            setContentView(R.layout.new_text);

            file = (EditText) findViewById(R.id.title_new);
            entry = (EditText) findViewById(R.id.entry_new);

            btn = (Button) findViewById(R.id.save_new);
            btn.setOnClickListener( new OnClickListener() {

                @Override
                public void onClick(View v) {

                    File myDir = getFilesDir();


                    NEWFILENAME = file.getText().toString();
                    if (NEWFILENAME.contentEquals("")){
                        NEWFILENAME = "UNTITLED";
                    }
                    NEWENTRY = entry.getText().toString();

                    try {

                        File file_new = new File(myDir+"/text/", NEWFILENAME);
                        file_new.createNewFile();

                        Log.i("file", file_new.toString());

                        if (file_new.mkdirs()) {
                            FileOutputStream fos = new FileOutputStream(file_new);

                            fos.write(NEWENTRY.getBytes());
                            fos.flush();
                            fos.close();
                        }

                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    Intent textPass = new Intent("com.example.TEXTMENU");
                    startActivity(textPass);
                }
            });

            }


 //That's for creating... then in other activity i'm reading

            @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.text_menu);

            btn = (Button) findViewById(R.id.newNote);
            listfinal = (ListView) findViewById(R.id.listView);

            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent textPass = new Intent("com.example.TEXTNEW");
                    startActivity(textPass);

                }
            });

            listfinal.setOnItemClickListener(this);

            File fileWithinMyDir = getApplicationContext().getFilesDir();


            loadbtn = (Button) findViewById(R.id.loadList);

            loadbtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    File myDir = getFilesDir();

                    File dir = new File(myDir + "/text/");

                    String[] files = dir.list();

                    //String[] files = getApplicationContext().fileList();
                    List<String> list = new ArrayList<String>();

                    for (int i =0; i < files.length; i++){
                        list.add(files[i]);
                    }
                    ArrayAdapter<String> ad = new ArrayAdapter<String>(TextMenu.this,  android.R.layout.simple_list_item_1,
                                    android.R.id.text1, list);

                    listfinal.setAdapter(ad);
                }
            });
            }
@覆盖
创建时受保护的void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.new_text);
文件=(EditText)findViewById(R.id.title\u new);
条目=(EditText)findViewById(R.id.entry\u new);
btn=(按钮)findViewById(R.id.save\u new);
btn.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
File myDir=getFilesDir();
NEWFILENAME=file.getText().toString();
if(NEWFILENAME.contentEquals(“”){
NEWFILENAME=“无标题”;
}
NEWENTRY=entry.getText().toString();
试一试{
File File_new=新文件(myDir+“/text/”,NEWFILENAME);
文件_new.createNewFile();
Log.i(“file”,file_new.toString());
if(文件\u new.mkdirs()){
FileOutputStream fos=新的FileOutputStream(新文件);
fos.write(NEWENTRY.getBytes());
fos.flush();
fos.close();
}
}catch(filenotfounde异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
Intent textPass=newintent(“com.example.TEXTMENU”);
星触觉(textPass);
}
});
}
//那是为了创造。。。然后在其他活动中,我正在阅读
@凌驾
创建时受保护的void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.text_菜单);
btn=(按钮)findViewById(R.id.newNote);
listfinal=(ListView)findViewById(R.id.ListView);
btn.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
Intent textPass=newintent(“com.example.TEXTNEW”);
星触觉(textPass);
}
});
listfinal.setOnItemClickListener(this);
File fileWithinMyDir=getApplicationContext().getFilesDir();
loadbtn=(按钮)findviewbyd(R.id.loadList);
loadbtn.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
File myDir=getFilesDir();
文件目录=新文件(myDir+“/text/”;
String[]files=dir.list();
//String[]files=getApplicationContext().fileList();
列表=新的ArrayList();
对于(int i=0;i
在我的android manifiest中,我拥有权限

              <uses-sdk
                    android:minSdkVersion="5"
                    android:targetSdkVersion="15" />

                <uses-permission android:name="android.hardware.camera" />
                <uses-permission android:name="android.permission.INTERNET" />
                <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
                <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

我不太确定您指的是哪个示例,但我这里有两个工作示例,其中至少有一个应该适合您的需要。 我在一个运行版本号2.1.A.0.435的X10、一个运行版本号7.0.A.1.303的Xperia T和一个运行版本号JZO54K的Nexus S上测试了这些

例1

    String filename = "myfile";
    String outputString = "Hello world!";

    try {
        FileOutputStream outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
        outputStream.write(outputString.getBytes());
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        FileInputStream inputStream = openFileInput(filename);
        BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            total.append(line);
        }
        r.close();
        inputStream.close();
        Log.d("File", "File contents: " + total);
    } catch (Exception e) {
        e.printStackTrace();
    }
例2

    String filename = "mysecondfile";
    String outputString = "Hello world!";
    File myDir = getFilesDir();

    try {
        File secondFile = new File(myDir + "/text/", filename);
        if (secondFile.getParentFile().mkdirs()) {
            secondFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(secondFile);

            fos.write(outputString.getBytes());
            fos.flush();
            fos.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        File secondInputFile = new File(myDir + "/text/", filename);
        InputStream secondInputStream = new BufferedInputStream(new FileInputStream(secondInputFile));
        BufferedReader r = new BufferedReader(new InputStreamReader(secondInputStream));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            total.append(line);
        }
        r.close();
        secondInputStream.close();
        Log.d("File", "File contents: " + total);
    } catch (Exception e) {
        e.printStackTrace();
    }

尽管我在清单文件中授予了读写权限,但三星Galaxy S7仍存在“权限被拒绝”问题。我通过进入手机设置>>应用>>[我的应用]并在许可的情况下允许“存储”来解决这个问题。之后工作正常。

你能提供日志吗?试着用
file.mkdirs()
call创建一个目录,你想把你的文件放在第一个目录下。为什么要检查
secondFile.getParentFile().mkdirs()
你能解释一下吗?如果你仍然对答案感兴趣:这个电话是为了确保,如果文件的路径存在,它将创建目录层次结构(如果需要)。如果有人仍然对此答案感兴趣:当以API 23+为目标时,必须在运行时请求写入外部存储权限。否则将出现“权限被拒绝”错误appear@LunarWatcher这是一个很好的观点,很好,你提出来了。我将更新答案,因为它可能会帮助将来来到这里的其他人。陷阱:如果应用程序的目标是API 23或更高版本,则必须在运行时请求写入外部存储权限。写入外部存储是一种危险的权限,这意味着必须请求它。