1. 程式人生 > >java位元組流和字元流操作檔案,指定編碼寫入和讀取,遞迴建立上層目錄

java位元組流和字元流操作檔案,指定編碼寫入和讀取,遞迴建立上層目錄

java的IO流分兩種流 
位元組流 InputStream OutputStream 
字元流 Reader Writer 
他們都是抽象類 
具體實現 
位元組流 FileInputStream FileOutputStream 
字元流 FileReader FileWriter  

       字元流處理的單元為2個位元組的Unicode字元,分別操作字元、字元陣列或字串,而位元組流處理單元為1個位元組,操作位元組和位元組陣列。所以字元流是由Java虛擬機器將位元組轉化為2個位元組的Unicode字元為單位的字元而成的,所以它對多國語言支援性比較好!如果是音訊檔案、圖片、歌曲,就用位元組流好點,如果是關係到中文(文字)的,用字元流好點.
     所有檔案的儲存是都是位元組(byte)的儲存,在磁碟上保留的並不是檔案的字元而是先把字元編碼成位元組,再儲存這些位元組到磁碟。在讀取檔案(特別是文字檔案)時,也是一個位元組一個位元組地讀取以形成位元組序列.
      位元組流可用於任何型別的物件,包括二進位制物件,而字元流只能處理字元或者字串; 2. 位元組流提供了處理任何型別的IO操作的功能,但它不能直接處理Unicode字元,而字元流就可以。

位元組流轉換成字元流可以用 InputSteamReader OutputStreamWriter 
轉換成BufferdReader BufferedWriter 他們具有緩衝區 
例如:讀取檔案 從位元組流輸入到字元流輸入 
定義一個位元組流:

// 定義一個指向D:/TEXT.TXT 的位元組流
FileInputStream fileInputStream = new FileInputStream("d:/text.txt"); 

//位元組流轉換成InputStreamReader 
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);

//InputStreamReader 轉換成帶快取的bufferedReader 
BufferedReader bufferedReader = new BufferedReader(inputSteamReader); 

Java的IO流分為字元流(Reader,Writer)和位元組流(InputStream,OutputStream),位元組流顧名思義位元組流就是將檔案的內容讀取到位元組陣列,然後再輸出到另一個檔案中。而字元流操作的最小單位則是字元。可以先看一下IO流的概述:

動態獲取檔案長度建立接收陣列,系統自動判定轉義目錄斜槓,講述位元組流、字元流、buffer流三種方式針對text檔案的寫入、讀取、建立、追加等操作

遞迴建立上層目錄

public static void mkDir(File file){
  if(file.getParentFile().exists()){
   file.mkdir();
  }else{
   mkDir(file.getParentFile());
   file.mkdir();
  }

檔案工具類如下

import java.io.File;
import java.io.IOException;
public class FileUtils {
public static final String encode = "UTF-8";
/**獲取目錄下的所有檔案和目錄列表完整地址輸出*/
public static void nowFileLists(String fileName) throws IOException{
File f=new File(fileName);
File[] str=f.listFiles();
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
/**判斷檔案是否存在*/
public static boolean exitsFile(String fileName) throws IOException{
File file = new File(fileName);
boolean flag = false;
if(file.exists()){
flag = true;
}
return flag;
}
/**判斷是否是資料夾*/
public static boolean isDirectory(String fileName) throws IOException{
File file = new File(fileName);
boolean flag = false;
//判斷是否是目錄   只有當資料夾存在的情況才能判斷
if(exitsFile(fileName)){
if(file.isDirectory()){
flag=true;
}
}
return flag;
}

/**建立檔案*/
public static void createFile(String fileName) throws IOException{
File file = new File(fileName);
file.createNewFile();
}
}

位元組流操作檔案

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 com.cn.utils.FileUtils;
public class ByteFiles {
/**
* 位元組流操作檔案
*/
public static void main(String [] args){
String fileName = "D:"+File.separator+"byteFile.txt";
try {
if(!FileUtils.exitsFile(fileName)){
FileUtils.createFile(fileName);
}
writeContext(fileName);
redaContext(fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
//寫入指定格式的檔案內容
public static void writeContext(String fileName) throws IOException{
File file = new File(fileName);
OutputStream outs = new FileOutputStream(file,true);
String content = "\r\n窗前明月光";
outs.write(content.getBytes("UTF-8"));
outs.close();

//寫入指定格式的檔案內容
public static void redaContext(String fileName) throws IOException{
File file = new File(fileName);
InputStream in = new FileInputStream(file);
byte b [] = new byte [(int) file.length()];
//位元組流讀取檔案方式一全部讀取
in.read(b);
in.close();
String content = new String(b);
System.out.println("byte方式一全部讀取:\r\n"+content);
//位元組流讀取檔案方式二  逐行讀取
InputStream inn = new FileInputStream(file);
byte bb [] = new byte [(int) file.length()];
int count =0;
int temp=0;
while((temp=inn.read())!=(-1)){
  bb[count++]=(byte)temp;
}
inn.close();
content = new String(bb);
System.out.println("byte方式二全部讀取:\r\n"+content);

}

字元流操作檔案

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import com.cn.utils.FileUtils;
public class CharFiles {
/**
* 字元流操作檔案
*/
public static void main(String [] args){
String fileName = "D:"+File.separator+"charFile.txt";
try {
if(!FileUtils.exitsFile(fileName)){
FileUtils.createFile(fileName);
}
writeContext(fileName);
redaContext(fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
//寫入指定格式的檔案內容
public static void writeContext(String fileName) throws IOException{
File file = new File(fileName);
OutputStream outs = new FileOutputStream(file,true);
OutputStreamWriter out = new OutputStreamWriter(outs,"UTF-8");
String content = "\r\n我是字元流寫入";
out.write(content);
out.close();

//寫入指定格式的檔案內容
public static void redaContext(String fileName) throws IOException{
File file = new File(fileName);
InputStreamReader inr = new InputStreamReader(new FileInputStream(file),"UTF-8");
char b [] = new char [(int) file.length()];
//字元流讀取檔案方式一全部讀取
inr.read(b);
inr.close();
String content = new String(b);
System.out.println("char方式一全部讀取:\r\n"+content);
//字元流讀取檔案方式二  逐行讀取
InputStreamReader inrr = new InputStreamReader(new FileInputStream(file),"UTF-8");
char bb [] = new char [(int) file.length()];
int count =0;
int temp=0;
while((temp=inrr.read())!=(-1)){
  bb[count++]=(char)temp;
}
inrr.close();
content = new String(bb);
System.out.println("char方式二全部讀取:\r\n"+content);

}

使用buffer流操作檔案

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import com.cn.utils.FileUtils;
public class BufferReadWriteFile {
public static void main(String[] args) {
String fileName = "D:"+File.separator+"buffer.txt";
try {
if(!FileUtils.exitsFile(fileName)){
FileUtils.createFile(fileName);
}
bufferWite(fileName);
bufferRead(fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
//使用buffer流進入寫入檔案
public static void bufferWite(String fileName){
OutputStreamWriter outt;
try {
outt = new OutputStreamWriter(new FileOutputStream(fileName,true),"UTF-8");
BufferedWriter wites = new BufferedWriter(outt);
wites.write("\r\n我是buffer流檔案操作");
wites.close();
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
} catch (FileNotFoundException e2) {
e2.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//使用buffer流進入讀取檔案
public static void bufferRead(String fileName){
        BufferedReader reader = null;
        InputStreamReader inputFileReader = null;
        String content = "";
        List<String> readContextList = new ArrayList<String>();
        String tempString = null;
        try {
            inputFileReader = new InputStreamReader(new FileInputStream(fileName),"UTF-8");
            reader = new BufferedReader(inputFileReader);
            // 一次讀入一行,直到讀入null為檔案結束
            while ((tempString = reader.readLine()) != null) {
                content += "\r\n"+tempString;
                readContextList.add(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
         
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        System.out.println(content);
}
}