Java 遍历文件夹,文件读写

遍历文件夹,输出文件夹下的所有文件和文件名:

import java.io.File;

public class Scaner {

	public static void main(String[] args) {
		printFiles(new File("E:\\practice\\ReadFileProperty"), 1);
	}
	public static void printFiles(File dir,int tab) {
		if(dir.isDirectory()) {
			File next[]=dir.listFiles();
			for (int i = 0; i < next.length; i++) {
				for (int j = 0; j < tab; j++) {
					System.out.print("|--");
				}
				System.out.println(next[i].getName());
				if(next[i].isDirectory()) {
					printFiles(next[i], tab+1);
				}
			}
		}
	}
}

 输出:

|--.classpath
|--.project
|--bin
|--|--ReadFileProperty.class
|--|--Scaner.class
|--src
|--|--ReadFileProperty.java
|--|--Scaner.java
|--test.txt

 


 

文件的读写操作:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class readFile {

	public static void main(String[] args) {
		File file=new File("test.txt");
		if(file.exists()) {
			System.out.println("文件存在");
			
			try {
				FileInputStream fis=new FileInputStream(file);
				InputStreamReader isr=new InputStreamReader(fis,"UTF-8");
				BufferedReader br=new BufferedReader(isr);
				 
				String line;
				while((line=br.readLine())!=null) {
					System.out.println(line);
				}
				br.close();
				isr.close();
				fis.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			File newFile=new File("newText.txt");
			FileOutputStream fos=new FileOutputStream(newFile);
			OutputStreamWriter osw=new OutputStreamWriter(fos,"UTF-8");
			BufferedWriter bw=new BufferedWriter(osw);
			
			bw.write("长歌行\n");
			bw.write("青青园中葵,朝露待日晞。\n");
			bw.write("阳春布德泽,万物生光辉。\n");
			bw.write("常恐秋节至,焜黄华叶衰。\n");
			bw.write("百川东到海,何时复西归? \n");
			bw.write("少壮不努力,老大徒伤悲。\n");
			
			bw.close();
			osw.close();
			fos.close();
			
			System.out.println("写入完成");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

 程序输出文件test.txt中的内容,并且把内容写入到新文件newText.txt中。

posted @ 2019-03-05 16:06  我的下铺刚田武  阅读(4420)  评论(0编辑  收藏  举报