Java IO流(一)

2014-11-24 10:14:25 · 作者: · 浏览: 5

[css]
自己整理的笔记,以后留着看。

1.创建文件

[java]
/**
* 创建文件
* 注意:创建文件之前判断文件是否存在,不然原来的文件要被覆盖。
*/
public static void createFileDemo(){
File file = new File(filepath);
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}

2. File类中的常量

[java]
File.pathSeparator指的是分隔连续多个路径字符串的分隔符,例如:
java -cp test.jar;abc.jar HelloWorld
就是指“;”
File.separator才是用来分隔同一个路径字符串中的目录的,例如:
C:\Program Files\Common Files
就是指“\”

3.用字节流的方式写入文件

[java]
/**
* 用字节流的方式写入文件
* 文件输出流的创建方式有两种,File对象或者文件绝对路径。
*/
public static void writeFileByStreamDemo(){

try {
FileOutputStream out = new FileOutputStream(filepath);
//另一种方式
//FileOutputStream out = new FileOutputStream(new File(filepath));
String str="你好";
out.write(str.getBytes());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

字节流貌似是没有缓冲的,在不调用out.close();的情况下,依然可以向文件中写入数据。字符流有缓冲。

4.FileOutputStream追加文件

[java]
/**
* 用FileOutputStream追加文件
* 创建文件输出流时指定第二个参数为true则为追加。new FileOutputStream(filepath,true);
*/
public static void appendFileByStreamDemo(){

try {
FileOutputStream out = new FileOutputStream(filepath,true);
String str="娅娅";
out.write(str.getBytes());
out.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


5.按流读取文件

[java]
/**
* 按流读取,当文件内容较少时,可以将其一次读取到字符数组里面
*/
public static void readFileByStreamDemo1(){

try {
File file = new File(filepath);
FileInputStream in = new FileInputStream(file);
byte[] b = new byte[(int) file.length()];
in.read(b);
System.out.println(new String(b));
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

[java]
byte[] b = new byte[(int) file.length()]; 定义和文件内容字节长度一样的字节数组,可以一次写入到数组,如果定义数组长度较长,会导致最后多输出空格。


6.按流循环读取,判断是否到达文件末尾

[java]
/**
* 按流循环读取,判断是否到达文件末尾
*/
public static void readFileByStream2(){
try {
File file = new File(filepath);
FileInputStream in = new FileInputStream(file);
byte[] b = new byte[1024];
int len = 0;
while((len = in.read(b))!=-1){
System.out.println(new String(b,0,len));
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
[java]
FileInputStream

判断是否读取到文件末尾的条件

(len = in.read(b))!=-1

 





 


7.字符输出流写入文件




        /**
* 字符输出流写入文件
*/
public static void writeFileByChar(){

try {
FileWriter fw = new FileWriter(filepath);
fw.write(new char[]{'中','国'});
fw.write(1);
fw.write("成功");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}


fw.write(-1); 这里我如果写入-1似乎不能成功,求解?


8.字符输入流读取文件 FileReader







        /**
* 按字符一次性读取
*/
pub