Java IO流(二)

2014-11-24 10:14:25 · 作者: · 浏览: 1
lic static void readFileByCharDemo1(){

try {
FileReader fr = new FileReader(filepath);
char[] c = new char[100];
int len = fr.read(c);
System.out.println("length:"+len);
System.out.println(new String(c,0,len));
fr.close();

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







9. FileReader循环读取,判断读取到文件末尾






        /**
* 循环读取,判断读取到文件末尾
*/
public static void readFileByChar2(){

try {
FileReader fr = new FileReader(filepath);
char[] c = new char[1024];
int len=0;
while((len= fr.read(c))!=-1){
System.out.println(new String(c,0,len));
}
fr.close();

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


10.复制文件







   /**
* 复制文件
* @param path1
* @param path2
*/
public static void copyFile(String path1,String path2){

try {
FileInputStream in = new FileInputStream(path1);
FileOutputStream out = new FileOutputStream(path2);

byte[] b = new byte[1024];
int len = 0;
while((len=in.read(b))!=-1){
out.write(b, 0, len);
}
in.close();
out.close();
} catch (IOException e) {
}
}





11. OutputStreramWriter 和 InputStreamReader






    OutputStreramWriter 和InputStreamReader类 

整个IO类中除了字节流和字符流还包括字节和字符转换流。

OutputStreramWriter将输出的字符流转化为字节流

InputStreamReader将输入的字节流转换为字符流


 public static void  OutputStreramWriterDemo1(){ 

try {
Writer writer = new OutputStreamWriter(new FileOutputStream(copypath));
writer.write("hello");
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}


 public static void InputStreamReaderDemo1(){ 

try {
Reader reader = new java.io.InputStreamReader(new FileInputStream(filepath));
char[] c = new char[100];
int len = 0;
len = reader.read(c);
System.out.println(new String(c,0,len));
reader.close();

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


12.打印流 PrintStream



   public static void printStreamDemo1(){ 

try {
PrintStream print = new PrintStream(new FileOutputStream(filepath));
print.print(true);
print.print("yaya");
String name="Rollen";
Integer age = 20;
// 格式化输出
print.printf("姓名:%s. 年龄:%d.", new Object[]{name,age});
print.close();
print.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}


13. PrintStream
输入输出重