import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
@SuppressWarnings("all")
public class IoDemo {
public static void main(String[] args) {
File file = new File("D:/java4/text.txt");
//创建文件夹
if(!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
System.out.println("文件夹创建成功!");
}
//创建文件
if(!file.exists()) {
try {
file.createNewFile();
System.out.println("文件创建成功!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Writer w = null;
try {
w = new FileWriter(file);
w.write("我好慌!aaa");
w.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
w.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(file.canRead() ? "文件可读" : "文件不可读");
Reader r = null;
char[] ch = new char[1024];
StringBuffer sbf = null;
try {
r = new FileReader(file);
try {
sbf = new StringBuffer();
int length = r.read(ch);//将字符读入char[]中
System.out.println(length);
while(length != -1) {
sbf.append(ch);
length = r.read(ch);
System.out.println(length);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
r.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(sbf);
}
}