zoukankan      html  css  js  c++  java
  • Android中对文本文件的读写处理

    1. 读取操作

    	String path = "/sdcard/foo.txt";
    String content = ""; //文件内容字符串
    //打开文件
    File file = new File(path);
    //如果path是传递过来的参数,可以做一个非目录的判断
    if (file.isDirectory()){
    Toast.makeText(EasyNote.this, "没有指定文本文件!", 1000).show();
    }
    else{
    try {
    InputStream instream = new FileInputStream(file);
    if (instream != null) {
    InputStreamReader inputreader = new InputStreamReader(instream);
    BufferedReader buffreader = new BufferedReader(inputreader);
    String line;
    //分行读取
    while (( line = buffreader.readLine()) != null) {
    content += line + "\n";
    }
    instream.close();
    } catch (java.io.FileNotFoundException e) {
    Toast.makeText(EasyNote.this, "文件不存在", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    2. 写入操作

    		String filePath = "/sdcard/foo2.txt";
    String content = "这是将要写入到文本文件的内容";
    //如果filePath是传递过来的参数,可以做一个后缀名称判断; 没有指定的文件名没有后缀,则自动保存为.txt格式
    if(!filePath.endsWith(".txt") && !filePath.endsWith(".log"))
    filePath += ".txt";
    //保存文件
    File file = new File(filePath);
    try {
    OutputStream outstream = new FileOutputStream(file);
    OutputStreamWriter out = new OutputStreamWriter(outstream);
    out.write(content);
    out.close();
    } catch (java.io.IOException e) {
    e.printStackTrace();
    }
  • 相关阅读:
    hdu 2485 Destroying the bus stations 迭代加深搜索
    hdu 2487 Ugly Windows 模拟
    hdu 2492 Ping pong 线段树
    hdu 1059 Dividing 多重背包
    hdu 3315 My Brute 费用流,费用最小且代价最小
    第四天 下载网络图片显示
    第三天 单元测试和数据库操作
    第二天 布局文件
    第一天 安卓简介
    Android 获取存储空间
  • 原文地址:https://www.cnblogs.com/wzc0066/p/2948243.html
Copyright © 2011-2022 走看看