package com.mtsoft;
import java.io.*;
import java.util.logging.Logger;
public class IODemo {
private FileOutputStream fileOutputStream;
private FileInputStream fileInputStream;
public IODemo() {
readFile();
}
public static void deleteFile(File folder) {
File[] files = folder.listFiles();
if(files != null) {
for(File f : files) {
if(f.isDirectory()) {
deleteFile(f);
} else {
f.delete();
}
}
folder.delete();
}
}
public void writeFile() {
String dirname = "D://io//java//demo";
//deleteFile(new File(dirname));
File dir = new File(dirname);
if(!dir.exists()) {
//创建目录
dir.mkdirs();
}
/* if(dir.isDirectory()) {
Logger.getGlobal().info("目录 " + dir);
String s[] = dir.list();
for(String str : s) {
File f = new File(dirname + "/" + str);
if(f.isDirectory()) {
Logger.getGlobal().info(str + " 是一个目录");
} else {
Logger.getGlobal().info(str + " 是一个文件");
}
}
} else {
Logger.getGlobal().info("dirname" + " 不是一个目录");
}*/
File file = new File("D://io//java//demo//HelloWorld.java");
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Logger.getGlobal().info(() -> "file:" + file.getAbsolutePath() + " 创建成功!");
}
try {
fileOutputStream = new FileOutputStream(file);
String content = "Hello, NingZuHuan!";
fileOutputStream.write(content.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void readFile() {
String file = "D://io//java//demo//HelloWorld.java";
try {
fileInputStream = new FileInputStream(file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
String line = null;
while((line = bufferedReader.readLine()) != null) {
Logger.getGlobal().info("line=" + line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new IODemo();
}
}
java文件操作
最新推荐文章于 2022-08-04 22:16:34 发布