版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
这段时间在牛客上做题发现了很多有意思的题,这一篇主要来实现IO流的有关程序题。
- 遍历输出指定路径下的所有文件
1.定义一个工具类,该类要求用户运行时输入一个路径。该工具类会将该路径下(及其子目录)的所有文件列出来。
import java.io.File;
import java.util.Scanner;
import com.sun.org.apache.bcel.internal.generic.F2D;
//遍历并输出文件
public class Tool1 {
public static void main(String[] args) {
System.out.println("please enter a path:");
String path;
Scanner sc = new Scanner(System.in);
path = sc.next();
File file = new File(path);
Dir(file);
}
public static void Dir(File file) {
File[] file1 = file.listFiles();
for (File f : file1) {
if (f.isDirectory()) {
Dir(f);
}
System.out.println(f.getName());
}
}
}
- 遍历并输出文件及文件夹个数
2.定义一个工具类,该类要求用户运行该程序时输入一个路径。该工具类会将该路径下的文件,文件夹的数量统计出来。
import java.io.File;
import java.util.Scanner;
import com.sun.org.apache.bcel.internal.generic.F2D;
//遍历并输出文件文件夹个数
public class Tool {
private static int n = 0;
private static int n1 = 0;
public static void main(String[] args) {
System.out.println("please enter a path:");
String path;
Scanner sc = new Scanner(System.in);
path = sc.next();
File file = new File(path);
Dir(file);
System.out.println(n-n1);
System.out.println(n1);
}
public static void Dir(File file) {
File[] file1 = file.listFiles();
for (File f : file1) {
if (f.isDirectory()) {
n1++;
Dir(f);
}
n++;
}
}
}
- 控制台以字符流保存文件及读取
3.控制台输入的仿记事本小程序
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import org.junit.Test;
public class Tool2 {
static String path ;
//控制台输入的仿记事本小程序
public static void main(String[] args) {
}
@Test
public void out() {
Scanner sc = new Scanner(System.in);
System.out.println("please enter the note path:");
path = sc.next();
BufferedReader br = null;
PrintWriter pw = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(path);
System.out.println("-------------------记事本----------------------");
String str = null;
while (!(str = br.readLine()).equals("exit")) {
pw.write(str+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
if (pw != null) {
pw.close();
}
}
}
@Test
public void in() {
Scanner sc = new Scanner(System.in);
System.out.println("please enter the note which you want to open:");
path = sc.next();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
String str = null;
while((str = br.readLine()) != null) {
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}