绝对路径和相对路径:
绝对路径一般从根目录开始,写全路径
相对路径一般从当前目录开始
FileInputStream
读文件的流程:
1、FileInputStream对象和String结果对象声明
2、创建FileInputStream对象(文件路劲或File对象)
3、读单字节或整个读到byte数组中
4、转成字符串
5、关闭FileInoutStream流
6、返回结果字符串
public static String readFile(String path){
// File f=new File(path);
FileInputStream fis=null;
String str=null;
try {
fis = new FileInputStream(path);
byte[] b=new byte[fis.available()];
// byte[] rst=null;
fis.read(b);
// for (int i = 0; i < b.length; i++) {
// if (b[i]==0)
// rst=Arrays.copyOf(b,i);
// }
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 readByOne(String path){
FileInputStream fis=null;
String str=null;
try {
fis=new FileInputStream(path);
StringBuffer sb=new StringBuffer();
int tmp;
while ((tmp=fis.read())!=-1){//read读的是ASCLL码值
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;
}
FileOutputStream
写文件的流程:
1、File对象转载文件路径
2、判断文件父级目录是否存在,不存在则创建
3、声明FileOutputStream对象
4、创建FileOutputStream对象(File对象,是否追加)
5、把要写的字符串转成byte数组,并写入输出流
6、关闭FileOutputStream流
public static void writeFile(String str,String path,boolean isAppend){
File f=new File(path);
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
FileOutputStream fos=null;
try {
fos=new FileOutputStream(f,isAppend);
byte[] b=str.getBytes();
fos.write(b);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}