java写文件 一行一行写。
package com.java456.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Scanner; public class TestJson { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); //str是遍历的路径 traverseFolder2(str); } public static void traverseFolder2(String path) { File file = new File(path); if (file.exists()) { File[] files = file.listFiles(); if (null == files || files.length == 0) { //System.out.println("文件夹是空的!"); return; } else { for (File file2 : files) { if (file2.isDirectory()) { System.out.println("文件夹:" + file2.getAbsolutePath()); write(file2.getAbsolutePath()); traverseFolder2(file2.getAbsolutePath()); } else { //System.out.println("文件:" + file2.getAbsolutePath()); } } } } else { System.out.println("文件不存在!"); } } public static void write(String str) { try { FileOutputStream fos=new FileOutputStream(new File("C:\\1.txt"),true);//true表示追加 没有则是覆盖 OutputStreamWriter osw=new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw=new BufferedWriter(osw); bw.write(str+System.getProperty("line.separator")); //注意关闭的先后顺序,先打开的后关闭,后打开的先关闭 bw.close(); osw.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
站长微信:xiaomao0055
站长QQ:14496453