IO流要注意的要点:
1、绝对路径和相对路径:
绝对路径:一般从根目录开始,写全路径
相对:从当前目录开始
2、FileInputStream读文件的流程:
FileInputStream 对象和String对象声明
创建FileInputStream对象(文件路径或者File对象)
读单字节或整个读到byte数组中;
转成字符串
关闭FileInputStream流
返回结果字符串
3、FileOutputStream写文件的流程:
Field对象装载文件路径
判断文件父级是否存在,不存在则创建
声明FileOutputStream对象
创建FileOutputStream对象(File对象,是否追加)
把要写的字符串转成byte数组,并写入输出流
写出要关闭FileOutputStream流
文件的创建
public static void creatFile(String path) {
File file = new File(path);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
creatFile("E:/文件/test3.txt");
}
输入流FileInputStream
下面代码展示了两种输入流的方法:reader和read.
public static String reader(String path) {
FileInputStream fis = null;
String str = null;
try {
fis =new FileInputStream(path);
int tmp=-1;
byte[] b = new byte[fis.available()];
fis.read(b);
str = new String(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}return str;
}
public static String read(String path) {
FileInputStream fis=null;
String str = null;
try {
StringBuffer sb = new StringBuffer();
fis=new FileInputStream(path);
int tmp ;
while ((tmp = fis.read()) != -1) {
char c=(char)tmp;
sb.append(c);
}
str =sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}return str;
}
public static void main(String[] args) {
System.out.println(read("E:/文件/我的青春谁做主.txt"));
}
输出流FileOutputStream
public static String wirte(String str, String path, boolean isAppend) {
File f = new File(path);
FileOutputStream fos = null;
if (!f.exists()) {
f.getParentFile().mkdirs();
}
try {
fos = new FileOutputStream(path,isAppend);
byte[] b = str.getBytes();
fos.write(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return str;
}
public static void main(String[] args) {
System.out.println(wirte("你好呀", "E:/测试/test.txt", true));
}