15.3文件的创建与删除
public static void main(String[] args) {
File file = new File("word.txt");
if(file.exists()) {
file.delete();
System.out.println("文件已删除");
}
else {
try {
file.createNewFile();
System.out.println("文件已创建");
} catch (IOException e) {
e.printStackTrace();
}
}
}
15.5 .带缓存的输入输出流
public static void main(String[] args) {
String content[] = {"好久不见","最近好吗","常联系"};
File file = new File("word.txt");
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bufw = new BufferedWriter(fw);
for(int k=0; k<content.length; k++) {
bufw.write(content[k]);
bufw.newLine();
}
bufw.close();
fw.close();
}catch(Exception e) {
e.printStackTrace();
}
try {
FileReader fr = new FileReader(file);
BufferedReader bufr = new BufferedReader(fr);
String s = null;
int i = 0;
while((s = bufr.readLine())!=null) {
i++;
System.out.println("第"+i+"行:"+s);
}
bufr.close();
fr.close();
}catch(Exception e) {
e.printStackTrace();
}
}
15.6数据输入输出流
try {
FileOutputStream fs = new FileOutputStream("word.txt");
DataOutputStream ds = new DataOutputStream(fs);
ds.writeUTF("使用writeUFT()方法写入数据");
ds.writeChars("使用writeChars()方法写入数据");
ds.writeBytes("使用writeBytes()方法写入数据");
ds.close();
FileInputStream fis = new FileInputStream("word.txt");
DataInputStream dis = new DataInputStream(fis);
System.out.println(dis.readUTF());
}catch(Exception e) {
e.printStackTrace();
}
获取文件信息
public static void main(String[] args) {
File file = new File("word.txt");
if(file.exists()) {
String name = file.getName();
long length = file.length();
boolean hidden = file.isHidden();
System.out.println("文件名称: "+name);
System.out.println("文件长度是: "+length);
System.out.println("该文件是隐藏文件吗: "+hidden);
}else {
System.out.println("文件不存在");
}
}