写入:
File writefile; String path = request.getSession().getServletContext().getRealPath("/") + "log"; String content = "123"; try { writefile = new File(path); if (writefile.exists() == false) // 如果文本文件不存在则创建它 { writefile.mkdir(); writefile = new File(path); // 重新实例化 } FileWriter filewriter = new FileWriter(writefile + "//log.txt");// 写入新的文件内容 filewriter.write(content); filewriter.close(); filewriter.flush(); } catch (Exception d) { System.out.println(d.getMessage()); }
request.getSession().getServletContext().getRealPath("/")为获取程序路径
读取:
try { String encoding = "GBK"; File file = new File(request.getSession().getServletContext().getRealPath("/") + "log" + "//log.txt"); if (file.isFile() && file.exists()) { // 判断文件是否存在 InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { System.out.println(lineTxt); } read.close(); } else { System.out.println("找不到指定的文件"); } } catch (Exception e) { System.out.println("读取文件内容出错"); e.printStackTrace(); }