写文件中的机器人到SD卡 [英] Write file to sdcard in android

查看:128
本文介绍了写文件中的机器人到SD卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建SD卡上的文件。在这里,我可以创建文件和读/写应用程序,但我想在这里,该文件应保存在SD卡的特定文件夹。我怎样才能做到这一点使用的FileOutputStream

  //创建文件
    公共无效的CreateFile(字符串名称)
    {
        尝试
        {
            新的FileOutputStream(文件名,真实).close();
        }赶上(FileNotFoundException异常E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }赶上(IOException异常E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }
    }

    //写入文件

    公共无效appendToFile(字符串dataAppend,字符串nameOfFile)抛出IOException异常
    {
        fosAppend = openFileOutput(nameOfFile,Context.MODE_APPEND);
        fosAppend.write(dataAppend.getBytes());
        fosAppend.write(System.getProperty(line.separator)的GetBytes());
        fosAppend.flush();
        fosAppend.close();
    }
 

解决方案

试试这个样子,

 尝试{
    文件newFolder =新的文件(Environment.getExternalStorageDirectory(),TestFolder);
    如果(!newFolder.exists()){
        newFolder.mkdir();
    }
    尝试 {
        档案文件=新的文件(newFolder,MyTest的+.TXT);
        file.createNewFile();
    }赶上(例外前){
        的System.out.println(如:+前);
    }
}赶上(例外五){
    的System.out.println(E:+ E);
}
 

I want to create a file on sdcard. Here I can create file and read/write it to the application, but what I want here is, the file should be saved on specific folder of sdcard. How can I do that using FileOutputStream?

// create file
    public void createfile(String name) 
    {
        try
        {
            new FileOutputStream(filename, true).close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // write to file

    public void appendToFile(String dataAppend, String nameOfFile) throws IOException 
    {
        fosAppend = openFileOutput(nameOfFile, Context.MODE_APPEND);
        fosAppend.write(dataAppend.getBytes());
        fosAppend.write(System.getProperty("line.separator").getBytes());
        fosAppend.flush();
        fosAppend.close();
    }

解决方案

Try like this,

try {
    File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
    if (!newFolder.exists()) {
        newFolder.mkdir();
    }
    try {
        File file = new File(newFolder, "MyTest" + ".txt");
        file.createNewFile();
    } catch (Exception ex) {
        System.out.println("ex: " + ex);
    }
} catch (Exception e) {
    System.out.println("e: " + e);
}

这篇关于写文件中的机器人到SD卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆