Java中读入文档和写入文档

    xiaoxiao2021-03-25  41

    1.将文本中的文字按行读入程序进行处理:

     public List<String> read(String dataPath) {

    List<String> readlist = new ArrayList<String>(); try { File file = new File(dataPath); if (file.isFile() && file.exists()) { InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8"); BufferedReader br = new BufferedReader(isr); String lineStr = null; while ((lineStr = br.readLine()) != null) { readlist.add(lineStr); } br.close(); isr.close(); } } catch (Exception e) { System.out.print(e); } return readlist;

    2.将程序运行结果按行写入文档

      try {     File f = new File("data/uncommonresult.txt"); if (!f.exists()){ f.createNewFile(); } OutputStreamWriter result = new OutputStreamWriter(new FileOutputStream(f),"UTF-8"); BufferedWriter write =  new BufferedWriter(result); for (int i = 0; i < ulst.size(); i++) { write.write(ulst.get(i)+"\n"); } write.close(); } catch (Exception e) { e.printStackTrace(); }

    转载请注明原文地址: https://ju.6miu.com/read-34704.html

    最新回复(0)