File类的操作

来源:互联网 发布:mac 多因素方差分析 编辑:程序博客网 时间:2024/06/06 07:06

 

public class TestFile {

//遍历浏览文件
@Test
public void scanFile() {
System.out.println("============");
String path = "/".trim();
File file = new File("H:\\");

File[] files = file.listFiles();
for (File current : files) {
System.out.println("--" + current.getName());
if (current.isDirectory()) {
File getFile = new File(current.getAbsoluteFile().toString());

if (getFile.listFiles() != null) {
File[] files2 = getFile.listFiles();
for (File current2 : files2) {
System.out.println("------------" + current2.getName());
}
}
}
}

}

@Test
public void testFile2() {
System.out.println("============");
String path = "d:\\".trim();
File file = new File(path);

String[] files = file.list();
for (String current : files) {
System.out.println("--" + current);

}

}

@Test
public void testFile3() {
System.out.println("============");
String path = "H:\\".trim();
File file = new File(path);

File[] files = file.listFiles();
for (File current : files) {
System.out.println("--" + current.getAbsolutePath().toString());
System.out.println("--" + current.getParent());

}

}



//创建文件

@Test
public void makeFile() {
System.out.println("============");
String path = "H:\\abc.txt".trim();

File file = new File(path);
System.out.println(file.getAbsolutePath());

if (!file.exists()) {
boolean result = file.mkdirs();
if (result) {

System.out.println("文件创建成功");
} else {

System.out.println("文件创建失败");
}

} else {
System.out.println("文件已经存在");
}

}


//写入文件
@Test
public void writeFile() {
try {
FileWriter fileWriter = new FileWriter("h:\\ceshi.txt".trim(), true);
int[] a = new int[] { 111111, 222222 };
for (int i = 0; i < a.length; i++) {
fileWriter.write(String.valueOf(a[i]) + "");
}
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
原创粉丝点击