zoukankan      html  css  js  c++  java
  • Android 写文件到手机

    1)// 在手机中创建文件
    FileOutputStream phone_outStream =this.openFileOutput("1.txt", Context.MODE_PRIVATE);
    phone_outStream.write("HELLO".getBytes());

    FileOutputStream phone_outStream1 =openFileOutput("1.txt", Context.MODE_APPEND); //追加模式继续写
    phone_outStream1.write(" world".getBytes());

    //读取并显示

    byte[] s= new byte[80];
    FileInputStream phone_inputStream =openFileInput("1.txt");
    phone_inputStream.read(s);    
    Toast.makeText(this, new String(s), Toast.LENGTH_SHORT).show();

    结论:不管手机data文件夹是否能在DDMS中看到东西, (没有root权限就会空空如也.)程序能够正常运行,并toast出正确内容.

    2)如果试图用该方法来写入到手机内部存储中,是不行的:

    java.io.FileNotFoundException: /2.txt: open failed: EROFS (Read-only file system)

    File f = new File("2.txt");
    FileOutputStream fs = new FileOutputStream( f ); //这句导致异常


    openFileOutput();是android的api, android.content.ContextWrapper.openFileOutput();

    FileOutputStream .是Java的类.  java.io.FileOutputStream

    此文转自:http://www.cnblogs.com/sinawear/archive/2012/11/26.html

    ==============================================

    public static void writeStringAsFile(final String fileContents, String fileName) {
            Context context = App.instance.getApplicationContext();
            try {
                FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
                out.write(fileContents);
                out.close();
            } catch (IOException e) {
                Logger.logError(TAG, e);
            }
        }

        public static String readFileAsString(String fileName) {
            Context context = App.instance.getApplicationContext();
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            BufferedReader in = null;

            try {
                in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
                while ((line = in.readLine()) != null) stringBuilder.append(line);

            } catch (FileNotFoundException e) {
                Logger.logError(TAG, e);
            } catch (IOException e) {
                Logger.logError(TAG, e);
            }

            return stringBuilder.toString();
        }

  • 相关阅读:
    一篇与面试官和蔼交流的深入了解JVM(JDK8)
    逆向工程,调试Hello World !程序(更新中)
    SpingBoot + Dubbo + Zookeeper实现简单分布式开发的应用
    Vue Axios 切片上传文件含实时进度
    Vue入门——常见指令及其详细代码示例
    女儿说要看烟花,但是政府规定不能放,程序员爸爸默默的拿起了键盘,程序员就是要为所欲为!
    逆向工程,调试Hello World !程序(更新中)
    python学习初始函数
    Python学习之装饰器
    Python学习之装饰器进阶
  • 原文地址:https://www.cnblogs.com/ansonz/p/3503765.html
Copyright © 2011-2022 走看看