文件读写操作

作者QQ:1095737364    QQ群:123300273     欢迎加入!
 
1.读取一行放入到List数组里面:
List<String> list = new ArrayList<String>();
File file = new File("F:/email.txt");
BufferedReader reader = null;
try {
  reader = new BufferedReader(new FileReader(file));
  String tempString = null;
  // 一次读入一行,直到读入null为文件结束
  while ((tempString = reader.readLine()) != null) {
    list.add(tempString);
  }
  reader.close();
} catch (IOException e) {
  e.printStackTrace();
} finally {
  if (reader != null) {
    try {
      reader.close();
    } catch (IOException e1) {
    }
  }
}

 

2.写入一行文字到文件
String tempString="";//要写入的数据
File file = new File("F:/email_suffx.txt");
try {
  //如果文件不存在就新建
  if(!file.exists()){
    file.createNewFile();
  }
  FileOutputStream out=new FileOutputStream(file,true); //如果追加方式用true
  out.write((tempString+"\r\n").getBytes("utf-8"));//注意需要转换对应的字符集
  out.close();
} catch (IOException e) {
  e.printStackTrace();
}

 

posted @ 2017-08-11 16:10  全栈九九六  阅读(162)  评论(0编辑  收藏  举报