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();
    }
  • 相关阅读:
    安装图形化界面
    cemtos安装python
    traceback说明
    python常用魔法函数
    python上传文件接口
    文件上传接口
    MongoDB安装与使用
    解决macOS系统向有跳板机的服务器传文件
    mac终端命令sftp
    linux下mysql服务安装
  • 原文地址:https://www.cnblogs.com/wzc0066/p/2948243.html
Copyright © 2011-2022 走看看