Java I/O流詳解

一、流的概念和作用。

流是一種有順序的,有起點和終點的字節集合,是對數據傳輸的總成或抽象。即數據在兩設備之間的傳輸稱之為流,流的本質是數據傳輸,根據數據傳輸的特性講流抽象為各種類,方便更直觀的進行數據操作。

二、IO流的分類。

根據數據處理類的不同分為:字符流和字節流。

根據數據流向不同分為:輸入流和輸出流。

三、字符流和字節流。

字符流的由來:因為數據編碼的不同,而有了對字符進行高效操作的流對象,其本質就是基于字節流讀取時,去查了指定的碼表。字符流和字節流的區別:

(1)讀寫單位不同:字節流一字節(8bit)為單位,字符流以字符為單位,根據碼表映射字符,一次可能讀多個字節。

(2)處理對象不同:字節流能處理所有類型的數據(例如圖片,avi),而字符流只能處理字符類型的數據。

(3)字節流操作的時候本身是不會用到緩沖區的,是對文件本身的直接操作。而字符流在操作的時候是會用到緩沖區的,通過緩沖區來操作文件。

結論:優先使用字節流,首先因為在硬盤上所有的文件都是以字節的形式進行傳輸或保存的,包括圖片等內容。但是字符流只是在內存中才會形成,所以在開發中字節流使用廣泛。

四、輸入流和輸出流。

對輸入流只能進行讀操作,對輸出流只能進行寫操作。程序中根據數據傳輸的不同特性使用不同的流。

五、輸入字節流InputStream。

InputStream是所有輸入字節流的父類,它是一個抽象類。

ByteArrayInputStream、StringBufferInputStream、FileInputStream 是三種基本的介質流,它們分別從Byte 數組、StringBuffer、和本地文件中讀取數據。PipedInputStream 是從與其它線程共用的管道中讀取數據,與Piped 相關的知識后續單獨介紹。
ObjectInputStream 和所有FilterInputStream的子類都是裝飾流(裝飾器模式的主角)。意思是FileInputStream類可以通過一個String路徑名創建一個對象,FileInputStream(String name)。而DataInputStream必須裝飾一個類才能返回一個對象,DataInputStream(InputStream in)。
講解Demo。

讀取文件,節省空間。

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */

package javaio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**

  • 字節流讀取文件內容

  • 節省空間的方式

  • @author xk
    */
    public class IoTest {

    public static void main(String[] args) throws IOException {

     String fileName = "D:"+File.separator+"hello.txt";
     File f = new File(fileName);
     InputStream in = new FileInputStream(f);
     byte[] b = new byte[(int)f.length()];
     in.read(b);
     System.err.println("長度為="+f.length());
     in.close();
     System.err.println(new String(b));
    

    }

}
逐一字節讀:
/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */

package javaio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**

  • 逐字節讀

  • 讀取文件內容,節省空間

  • @author xk
    */
    public class IoTest {

    public static void main(String[] args) throws IOException {

     String fileName = "D:"+File.separator+"hello.txt";
     File f = new File(fileName);
     InputStream in = new FileInputStream(f);
     byte[] b = new byte[(int)f.length()];
     for(int i = 0;i< b.length;i++){
         b[i] = (byte) in.read();
     }
     in.close();
     System.err.println(new String(b));
    

    }

}
注意:上面的幾個例子都是在知道文件的內容多大,然后才展開的,有時候我們不知道文件有多大,這種情況下,我們需要判斷是否獨到文件的末尾。
/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */

package javaio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**

  • 逐字節讀取文件內容

  • @author xk
    */
    public class IoTest {

    public static void main(String[] args) throws IOException {

     String fileName = "D:"+File.separator+"hello.txt";
     File f = new File(fileName);
     InputStream in = new FileInputStream(f);
     byte[] b = new byte[1024];
     int count = 0;
     int temp = 0;
     while((temp = in.read())!=(-1)){
         b[count++] = (byte)temp;
     }
     in.close();
     System.err.println(new String(b));
    

    }

}
注意:當讀到文件末尾的時候會返回-1.正常情況下是不會返回-1的。
PushBackInputStream回退流操作:

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package javaio;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;

/**

  • @author xk
    */
    public class IoTest {

    public static void main(String[] args) throws IOException {

     String str = "hello,rollenholt";
     PushbackInputStream push = null;
     ByteArrayInputStream bat = null;
     bat = new ByteArrayInputStream(str.getBytes());
     push = new PushbackInputStream(bat);
     int temp = 0;
     while ((temp = push.read()) != -1) {
         if (temp == ',') {
             push.unread(temp);
             temp = push.read();
             System.out.print("(回退" + (char) temp + ") ");
         } else {
             System.out.print((char) temp);
         }
     }
    

    }
    }
    六、輸出字節流OutputStream。
    OutputStream是所有輸出流的父類,它是一個抽象類。

ByteArrayOutputStream、FileOutputStream是兩種基本的介質流,它們分別向Byte 數組、和本地文件中寫入數據。PipedOutputStream 是向與其它線程共用的管道中寫入數據,
ObjectOutputStream 和所有FilterOutputStream的子類都是裝飾流。具體例子跟InputStream是對應的。

實例Demo:

向文件中寫入字符串:

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package javaio;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**

  • @author xk
    */
    public class OutputStreamDemo {

    public static void main(String[] args) throws IOException {

     String fileName = "D:" + File.separator + "hello.txt";
     File f = new File(fileName);
     OutputStream os = new FileOutputStream(f);
     String str = "xukuntest";
     byte[] b = str.getBytes();
     os.write(b);
     os.close();
    

    }
    }
    /**

  • 字節流

  • 向文件中一個字節一個字節的寫入字符串

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String fileName="D:"+File.separator+"hello.txt";
    File f=new File(fileName);
    OutputStream out =new FileOutputStream(f);
    String str="Hello World?。?;
    byte[] b=str.getBytes();
    for (int i = 0; i < b.length; i++) {
    out.write(b[i]);
    }
    out.close();
    }
    }
    /**

  • 字節流

  • 向文件中追加新內容:

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String fileName="D:"+File.separator+"hello.txt";
    File f=new File(fileName);
    OutputStream out =new FileOutputStream(f,true);//true表示追加模式,否則為覆蓋
    String str="Rollen";
    //String str="\r\nRollen"; 可以換行
    byte[] b=str.getBytes();
    for (int i = 0; i < b.length; i++) {
    out.write(b[i]);
    }
    out.close();
    }
    }
    /**

  • 文件的復制

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    if(args.length!=2){
    System.out.println("命令行參數輸入有誤,請檢查");
    System.exit(1);
    }
    File file1=new File(args[0]);
    File file2=new File(args[1]);

    if(!file1.exists()){
    System.out.println("被復制的文件不存在");
    System.exit(1);
    }
    InputStream input=new FileInputStream(file1);
    OutputStream output=new FileOutputStream(file2);
    if((input!=null)&&(output!=null)){
    int temp=0;
    while((temp=input.read())!=(-1)){
    output.write(temp);
    }
    }
    input.close();
    output.close();
    }
    }
    /**

  • 使用內存操作流將一個大寫字母轉化為小寫字母

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String str="ROLLENHOLT";
    ByteArrayInputStream input=new ByteArrayInputStream(str.getBytes());
    ByteArrayOutputStream output=new ByteArrayOutputStream();
    int temp=0;
    while((temp=input.read())!=-1){
    char ch=(char)temp;
    output.write(Character.toLowerCase(ch));
    }
    String outStr=output.toString();
    input.close();
    output.close();
    System.out.println(outStr);
    }
    }
    /**

  • 驗證管道流

  • /
    import java.io.
    ;

/**

  • 消息發送類
  • */
    class Send implements Runnable{
    private PipedOutputStream out=null;
    public Send() {
    out=new PipedOutputStream();
    }
    public PipedOutputStream getOut(){
    return this.out;
    }
    public void run(){
    String message="hello , Rollen";
    try{
    out.write(message.getBytes());
    }catch (Exception e) {
    e.printStackTrace();
    }try{
    out.close();
    }catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

/**

  • 接受消息類
  • /
    class Recive implements Runnable{
    private PipedInputStream input=null;
    public Recive(){
    this.input=new PipedInputStream();
    }
    public PipedInputStream getInput(){
    return this.input;
    }
    public void run(){
    byte[] b=new byte[1000];
    int len=0;
    try{
    len=this.input.read(b);
    }catch (Exception e) {
    e.printStackTrace();
    }try{
    input.close();
    }catch (Exception e) {
    e.printStackTrace();
    }
    System.out.println("接受的內容為 "+(new String(b,0,len)));
    }
    }
    /
    *
  • 測試類
  • */
    class hello{
    public static void main(String[] args) throws IOException {
    Send send=new Send();
    Recive recive=new Recive();
    try{
    //管道連接
    send.getOut().connect(recive.getInput());
    }catch (Exception e) {
    e.printStackTrace();
    }
    new Thread(send).start();
    new Thread(recive).start();
    }
    }
    DataOutputStream類示例
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    public class DataOutputStreamDemo{
    public static void main(String[] args) throws IOException{
    File file = new File("d:" + File.separator +"hello.txt");
    char[] ch = { 'A', 'B', 'C' };
    DataOutputStream out = null;
    out = new DataOutputStream(new FileOutputStream(file));
    for(char temp : ch){
    out.writeChar(temp);
    }
    out.close();
    }
    }
    java.util.zip.ZipOutputStream
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;

public class ZipOutputStreamDemo1{
public static void main(String[] args) throws IOException{
File file = new File("d:" + File.separator +"hello.txt");
File zipFile = new File("d:" + File.separator +"hello.zip");
InputStream input = new FileInputStream(file);
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
zipFile));
zipOut.putNextEntry(new ZipEntry(file.getName()));
// 設置注釋
zipOut.setComment("hello");
int temp = 0;
while((temp = input.read()) != -1){
zipOut.write(temp);
}
input.close();
zipOut.close();
}
}
【案例】ZipOutputStream類壓縮多個文件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**

  • 一次性壓縮多個文件
  • */
    public class ZipOutputStreamDemo2{
    public static void main(String[] args) throws IOException{
    // 要被壓縮的文件夾
    File file = new File("d:" + File.separator +"temp");
    File zipFile = new File("d:" + File.separator + "zipFile.zip");
    InputStream input = null;
    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
    zipFile));
    zipOut.setComment("hello");
    if(file.isDirectory()){
    File[] files = file.listFiles();
    for(int i = 0; i < files.length; ++i){
    input = newFileInputStream(files[i]);
    zipOut.putNextEntry(newZipEntry(file.getName()
    + File.separator +files[i].getName()));
    int temp = 0;
    while((temp = input.read()) !=-1){
    zipOut.write(temp);
    }
    input.close();
    }
    }
    zipOut.close();
    }
    }
    【案例】ZipFile類展示
    import java.io.File;
    import java.io.IOException;
    import java.util.zip.ZipFile;

/**
*ZipFile演示

  • */
    public class ZipFileDemo{
    public static void main(String[] args) throws IOException{
    File file = new File("d:" + File.separator +"hello.zip");
    ZipFile zipFile = new ZipFile(file);
    System.out.println("壓縮文件的名稱為:" + zipFile.getName());
    }
    }
    【案例】解壓縮文件(壓縮文件中只有一個文件的情況)
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;

/**

  • 解壓縮文件(壓縮文件中只有一個文件的情況)
  • */
    public class ZipFileDemo2{
    public static void main(String[] args) throws IOException{
    File file = new File("d:" + File.separator +"hello.zip");
    File outFile = new File("d:" + File.separator +"unZipFile.txt");
    ZipFile zipFile = new ZipFile(file);
    ZipEntry entry =zipFile.getEntry("hello.txt");
    InputStream input = zipFile.getInputStream(entry);
    OutputStream output = new FileOutputStream(outFile);
    int temp = 0;
    while((temp = input.read()) != -1){
    output.write(temp);
    }
    input.close();
    output.close();
    }
    }
    【案例】ZipInputStream類解壓縮一個壓縮文件中包含多個文件的情況
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipInputStream;

/**

  • 解壓縮一個壓縮文件中包含多個文件的情況
  • */
    public class ZipFileDemo3{
    public static void main(String[] args) throws IOException{
    File file = new File("d:" +File.separator + "zipFile.zip");
    File outFile = null;
    ZipFile zipFile = new ZipFile(file);
    ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));
    ZipEntry entry = null;
    InputStream input = null;
    OutputStream output = null;
    while((entry = zipInput.getNextEntry()) != null){
    System.out.println("解壓縮" + entry.getName() + "文件");
    outFile = new File("d:" + File.separator + entry.getName());
    if(!outFile.getParentFile().exists()){
    outFile.getParentFile().mkdir();
    }
    if(!outFile.exists()){
    outFile.createNewFile();
    }
    input = zipFile.getInputStream(entry);
    output = new FileOutputStream(outFile);
    int temp = 0;
    while((temp = input.read()) != -1){
    output.write(temp);
    }
    input.close();
    output.close();
    }
    }
    }
    七.幾個特殊的輸入流類分析
    LineNumberInputStream
    主要完成從流中讀取數據時,會得到相應的行號,至于什么時候分行、在哪里分行是由改類主動確定的,并不是在原始中有這樣一個行號。在輸出部分沒有對應的部分,我們完全可以自己建立一個LineNumberOutputStream,在最初寫入時會有一個基準的行號,以后每次遇到換行時會在下一行添加一個行號,看起來也是可以的。好像更不入流了。
    PushbackInputStream
    其功能是查看最后一個字節,不滿意就放入緩沖區。主要用在編譯器的語法、詞法分析部分。輸出部分的BufferedOutputStream 幾乎實現相近的功能。
    StringBufferInputStream
    已經被Deprecated,本身就不應該出現在InputStream部分,主要因為String 應該屬于字符流的范圍。已經被廢棄了,當然輸出部分也沒有必要需要它了!還允許它存在只是為了保持版本的向下兼容而已。
    SequenceInputStream
    可以認為是一個工具類,將兩個或者多個輸入流當成一個輸入流依次讀取。完全可以從IO 包中去除,還完全不影響IO 包的結構,卻讓其更“純潔”――純潔的Decorator 模式。
    【案例】將兩個文本文件合并為另外一個文本文件
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.SequenceInputStream;

/**

  • 將兩個文本文件合并為另外一個文本文件
  • /
    public class SequenceInputStreamDemo{
    public static voidmain(String[] args) throws IOException{
    File file1 = newFile("d:" + File.separator + "hello1.txt");
    File file2 = newFile("d:" + File.separator + "hello2.txt");
    File file3 = newFile("d:" + File.separator + "hello.txt");
    InputStream input1 =new FileInputStream(file1);
    InputStream input2 =new FileInputStream(file2);
    OutputStream output =new FileOutputStream(file3);
    // 合并流
    SequenceInputStreamsis = new SequenceInputStream(input1, input2);
    int temp = 0;
    while((temp =sis.read()) != -1){
    output.write(temp);
    }
    input1.close();
    input2.close();
    output.close();
    sis.close();
    }
    }
    PrintStream
    也可以認為是一個輔助工具。主要可以向其他輸出流,或者FileInputStream 寫入數據,本身內部實現還是帶緩沖的。本質上是對其它流的綜合運用的一個工具而已。一樣可以踢出IO 包!System.err和System.out 就是PrintStream 的實例!
    【案例】使用PrintStream進行格式化輸出
    /
    *
  • 使用PrintStream進行輸出
  • 并進行格式化
  • /
    import java.io.
    ;
    class hello {
    public static void main(String[] args) throws IOException {
    PrintStream print = new PrintStream(new FileOutputStream(newFile("d:"
    + File.separator +"hello.txt")));
    String name="Rollen";
    int age=20;
    print.printf("姓名:%s. 年齡:%d.",name,age);
    print.close();
    }
    }
    【案例】使用OutputStream向屏幕上輸出內容
    /**
  • 使用OutputStream向屏幕上輸出內容
  • /
    import java.io.
    ;
    class hello {
    public static void main(String[] args) throws IOException {
    OutputStream out=System.out;
    try{
    out.write("hello".getBytes());
    }catch (Exception e) {
    e.printStackTrace();
    }
    try{
    out.close();
    }catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    【案例】輸入輸出重定向
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;

/**

  • 為System.out.println()重定向輸出
  • /
    public class systemDemo{
    public static void main(String[] args){
    // 此刻直接輸出到屏幕
    System.out.println("hello");
    File file = new File("d:" + File.separator +"hello.txt");
    try{
    System.setOut(new PrintStream(new FileOutputStream(file)));
    }catch(FileNotFoundException e){
    e.printStackTrace();
    }
    System.out.println("這些內容在文件中才能看到哦!");
    }
    【案例】System.in重定向
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    /
    *
    *System.in重定向
  • /
    public class systemIn{
    public static void main(String[] args){
    File file = new File("d:" + File.separator +"hello.txt");
    if(!file.exists()){
    return;
    }else{
    try{
    System.setIn(newFileInputStream(file));
    }catch(FileNotFoundException e){
    e.printStackTrace();
    }
    byte[] bytes = new byte[1024];
    int len = 0;
    try{
    len = System.in.read(bytes);
    }catch(IOException e){
    e.printStackTrace();
    }
    System.out.println("讀入的內容為:" + new String(bytes, 0, len));
    }
    }
    }
    八.字符輸入流Reader
    定義和說明:
    在上面的繼承關系圖中可以看出:
    Reader 是所有的輸入字符流的父類,它是一個抽象類。
    CharReader、StringReader是兩種基本的介質流,它們分別將Char 數組、String中讀取數據。PipedReader 是從與其它線程共用的管道中讀取數據。
    BufferedReader 很明顯就是一個裝飾器,它和其子類負責裝飾其它Reader 對象。
    FilterReader 是所有自定義具體裝飾流的父類,其子類PushbackReader 對Reader 對象進行裝飾,會增加一個行號。
    InputStreamReader 是一個連接字節流和字符流的橋梁,它將字節流轉變為字符流。FileReader可以說是一個達到此功能、常用的工具類,在其源代碼中明顯使用了將FileInputStream 轉變為Reader 的方法。我們可以從這個類中得到一定的技巧。Reader 中各個類的用途和使用方法基本和InputStream 中的類使用一致。后面會有Reader 與InputStream 的對應關系。
    【案例】以循環方式從文件中讀取內容
    /
    *
  • 字符流
  • 從文件中讀出內容
  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String fileName="D:"+File.separator+"hello.txt";
    File f=new File(fileName);
    char[] ch=new char[100];
    Reader read=new FileReader(f);
    int temp=0;
    int count=0;
    while((temp=read.read())!=(-1)){
    ch[count++]=(char)temp;
    }
    read.close();
    System.out.println("內容為"+new String(ch,0,count));
    }
    }
    【案例】BufferedReader的小例子
    注意:BufferedReader只能接受字符流的緩沖區,因為每一個中文需要占據兩個字節,所以需要將System.in這個字節輸入流變為字符輸入流,采用:
    BufferedReader buf = new BufferedReader(newInputStreamReader(System.in));
    下面是一個實例:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**

  • 使用緩沖區從鍵盤上讀入內容
  • */
    public class BufferedReaderDemo{
    public static void main(String[] args){
    BufferedReader buf = new BufferedReader(
    newInputStreamReader(System.in));
    String str = null;
    System.out.println("請輸入內容");
    try{
    str = buf.readLine();
    }catch(IOException e){
    e.printStackTrace();
    }
    System.out.println("你輸入的內容是:" + str);
    }
    }
    【案例】Scanner類從文件中讀出內容
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

/**
*Scanner的小例子,從文件中讀內容

  • */
    public class ScannerDemo{
    public static void main(String[] args){

    File file = new File("d:" + File.separator +"hello.txt");
    Scanner sca = null;
    try{
    sca = new Scanner(file);
    }catch(FileNotFoundException e){
    e.printStackTrace();
    }
    String str = sca.next();
    System.out.println("從文件中讀取的內容是:" + str);
    }
    }
    九.字符輸出流Writer
    定義和說明:
    在上面的關系圖中可以看出:
    Writer 是所有的輸出字符流的父類,它是一個抽象類。
    CharArrayWriter、StringWriter 是兩種基本的介質流,它們分別向Char 數組、String 中寫入數據。
    PipedWriter 是向與其它線程共用的管道中寫入數據,
    BufferedWriter 是一個裝飾器為Writer 提供緩沖功能。
    PrintWriter 和PrintStream 極其類似,功能和使用也非常相似。
    OutputStreamWriter 是OutputStream 到Writer 轉換的橋梁,它的子類FileWriter 其實就是一個實現此功能的具體類(具體可以研究一SourceCode)。功能和使用和OutputStream 極其類似,后面會有它們的對應圖。
    實例操作演示:
    【案例】向文件中寫入數據
    /**

  • 字符流

  • 寫入數據

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String fileName="D:"+File.separator+"hello.txt";
    File f=new File(fileName);
    Writer out =new FileWriter(f);
    String str="hello";
    out.write(str);
    out.close();
    }
    }
    注意:這個例子上之前的例子沒什么區別,只是你可以直接輸入字符串,而不需要你將字符串轉化為字節數組。當你如果想問文件中追加內容的時候,可以使用將上面的聲明out的哪一行換為:
    Writer out =new FileWriter(f,true);
    這樣,當你運行程序的時候,會發現文件內容變為:hellohello如果想在文件中換行的話,需要使用“\r\n”比如將str變為String str="\r\nhello";這樣文件追加的str的內容就會換行了。
    十.字符流與字節流轉換
    轉換流的特點:
    (1)其是字符流和字節流之間的橋梁
    (2)可對讀取到的字節數據經過指定編碼轉換成字符
    (3)可對讀取到的字符數據經過指定編碼轉換成字節
    何時使用轉換流?
    當字節和字符之間有轉換動作時;
    流操作的數據需要編碼或解碼時。
    具體的對象體現:
    InputStreamReader:字節到字符的橋梁
    OutputStreamWriter:字符到字節的橋梁
    這兩個流對象是字符體系中的成員,它們有轉換作用,本身又是字符流,所以在構造的時候需要傳入字節流對象進來。
    字節流和字符流轉換實例:
    【案例】將字節輸出流轉化為字符輸出流
    /**

  • 將字節輸出流轉化為字符輸出流

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String fileName= "d:"+File.separator+"hello.txt";
    File file=new File(fileName);
    Writer out=new OutputStreamWriter(new FileOutputStream(file));
    out.write("hello");
    out.close();
    }
    }
    【案例】將字節輸入流轉換為字符輸入流
    /**

  • 將字節輸入流變為字符輸入流

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String fileName= "d:"+File.separator+"hello.txt";
    File file=new File(fileName);
    Reader read=new InputStreamReader(new FileInputStream(file));
    char[] b=new char[100];
    int len=read.read(b);
    System.out.println(new String(b,0,len));
    read.close();
    }
    }
    十一.File類
    File類是對文件系統中文件以及文件夾進行封裝的對象,可以通過對象的思想來操作文件和文件夾。 File類保存文件或目錄的各種元數據信息,包括文件名、文件長度、最后修改時間、是否可讀、獲取當前文件的路徑名,判斷指定文件是否存在、獲得當前目錄中的文件列表,創建、刪除文件和目錄等方法。
    【案例 】創建一個文件
    import java.io.;
    class hello{
    public static void main(String[] args) {
    File f=new File("D:\hello.txt");
    try{
    f.createNewFile();
    }catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    【案例2】File類的兩個常量
    import java.io.
    ;
    class hello{
    public static void main(String[] args) {
    System.out.println(File.separator);
    System.out.println(File.pathSeparator);
    }
    }
    此處多說幾句:有些同學可能認為,我直接在windows下使用\進行分割不行嗎?當然是可以的。但是在linux下就不是\了。所以,要想使得我們的代碼跨平臺,更加健壯,所以,大家都采用這兩個常量吧,其實也多寫不了幾行。
    【案例3】File類中的常量改寫案例1的代碼:

import java.io.;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
try{
f.createNewFile();
}catch (Exception e) {
e.printStackTrace();
}
}
}
【案例4】刪除一個文件(或者文件夾)
import java.io.
;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
if(f.exists()){
f.delete();
}else{
System.out.println("文件不存在");
}

}
}
【案例5】創建一個文件夾
/**

  • 創建一個文件夾
  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) {
    String fileName="D:"+File.separator+"hello";
    File f=new File(fileName);
    f.mkdir();
    }
    }
    【案例6】列出目錄下的所有文件
    /**
  • 使用list列出指定目錄的全部文件
  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) {
    String fileName="D:"+File.separator;
    File f=new File(fileName);
    String[] str=f.list();
    for (int i = 0; i < str.length; i++) {
    System.out.println(str[i]);
    }
    }
    }

轉自:http://blog.csdn.net/u012815721/article/details/25279613

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,572評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,071評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,409評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,569評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,360評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,895評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,979評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,123評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,643評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,559評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,742評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,250評論 5 356
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,981評論 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,363評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,622評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,354評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,707評論 2 370

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,776評論 18 139
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,707評論 18 399
  • ¥開啟¥ 【iAPP實現進入界面執行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,477評論 0 17
  • 昨天,一朋友的電話把我從夢里拉醒。 他說:我好痛苦睡不著啊,我這人怎么總是擅長于失去一些重要的東西。 我不解:失去...
    非謂語閱讀 687評論 0 2
  • 1.查詢等待時間縮短數秒: 之前幾秒現在幾秒 做了哪些方面的優化? 答:之前少則5秒多則10秒以上,現在一般情況下...
    小公子閱讀 291評論 0 0