Java读取文件内容和写入内容到文件

来源:互联网 发布:sql中别名 编辑:程序博客网 时间:2024/06/06 05:05

Java读取文件内容方法和写入内容到文件方法

/** * One.txt中的数据如下: * 1 * 2 * 3 * 4 * 5 * ----------------- * 读操作方法 */@Testpublic void readFileToList2() {File file = new File("C:\\Users\\Desktop\\One.txt");System.out.println("文件绝对路径 :"+file.getAbsolutePath());List<String> listStr = new ArrayList<String>();BufferedReader br = null;String str = null;try {br = new BufferedReader(new FileReader(file));while ((str = br.readLine())!= null) {listStr.add(str);}} catch (FileNotFoundException e) {e.printStackTrace();}catch (IOException e) {e.printStackTrace();}System.out.println(listStr);writeListToFile(listStr);// 调用写操作方法}/** * 实现写操作方法 */private void writeListToFile(List<String> listStr) {File file = new File("C:\\Users\\Desktop\\Azzan.txt");// 要写入的文件路径if (!file.exists()) {// 判断文件是否存在try {file.createNewFile();// 如果文件不存在创建文件System.out.println("文件"+file.getName()+"不存在已为您创建!");} catch (IOException e) {System.out.println("创建文件异常!");e.printStackTrace();}} else {System.out.println("文件"+file.getName()+"已存在!");}for (String str : listStr) {// 遍历listStr集合FileOutputStream fos = null;PrintStream ps = null;try {fos = new FileOutputStream(file,true);// 文件输出流追加ps = new PrintStream(fos);} catch (FileNotFoundException e) {e.printStackTrace();}String string  = str + "\r\n";// +换行ps.print(string); // 执行写操作ps.close();// 关闭流}System.out.println("文件写入完毕!");}

原创粉丝点击