今天做了io相关的练习题
遇到的主要问题是网上的例子有点老了,放到编译器里并不能运行,不过还是解决了
package com.xykj.lesson1;
import java.io.File;
import java.io.IOException;
public class Test1 {
public static void main(String[] args) {
File file=new File("D:","HelloWorld.txt");
boolean isCreate;
try {
isCreate = file.createNewFile();
if (isCreate) {
System.out.println("创建文件成功!");
}else {
System.out.println("创建文件失败!文件已经存在");
}
} catch (IOException e) {
System.out.println("创建文件失败!");
}
if (file.isFile()) {
System.out.println("这是一个文件");
} else {
System.out.println("这是一个目录");
}
File file2=new File("D:/IOTest");
file2.mkdirs();
if (file.renameTo(file2)) {
System.out.println("文件移动成功!");
} else {
System.out.println("文件移动失败");
}
String[] arr=file2.list();
for (String string : arr) {
System.out.println(string);
}
}
}
package com.xykj.lesson2;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FileUtils {
public static List getAllFiles(String dir){
List< File >files=new ArrayList();
File file=new File(dir);
if (file.exists()&&file.isDirectory()) {
longErgodic(file,files);
}
return files;
}
private static void longErgodic(File file, List files) {
File[] fillArr=file.listFiles();
if (fillArr==null) {
return;
}
for (File file2 : fillArr) {
files.add(file2);
longErgodic(file2, files);
}
}
}
package com.xykj.lesson2;
import java.io.File;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
Listlist=FileUtils.getAllFiles("D:");
for (File file : list) {
System.out.println(file);
}
}
}
package com.xykj.lesson3;
import java.io.File;
import java.util.List;
import com.xykj.lesson2.FileUtils;
public class Test3 {
public static void main(String[] args) {
Listlist=FileUtils.getAllFiles(".");
for (File file : list) {
if (file.toString().endsWith(".java")) {
System.out.println(file.getName());
}
}
}
}
package com.xykj.lesson4;
import java.io.File;
import java.io.FileInputStream;
public class Tset4 {
public static void main(String[] args) {
File file = new File("D:\notePad\aa.txt");
try {
FileInputStream fis = new FileInputStream(file);
int len = 0;
byte[] buf = new byte[1024];
StringBuffer sb = new StringBuffer();
while ((len = fis.read(buf)) != -1) {
sb.append(new String(buf, 0, len));
}
System.out.println(sb);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.xykj.lesson5;
import java.io.File;
import java.io.FileOutputStream;
public class Test5 {
public static void main(String[] args) {
File file = new File("D:/Hello.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write("HelloJavaWorld你好世界".getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}