java讀取文件--一個字節一個字節讀取

 一:什麼是字節?java

字節(Byte)是計算信息技術用於計量存儲容量和傳輸容量的一種計量單位,一個字節等於8位二進制數。1byte=8bit=8個0/1ide

二:字母、數字、漢字與字節關係?spa

1byte=1個字母=1個數字it

2byte=1個漢字io

所以若是按照字節一個字節一個字節讀取文件的話,讀取中文輸出的時候會出現亂碼(由於一個漢字佔二個字節)。class

三:讀取字節的方式--用來讀取數字或者字母代碼以下:import

package com.javaIo;亂碼

import java.io.File;file

import java.io.FileInputStream;二進制

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

 

/**

 * @按照字節讀取文件

 * @author zl

 *

 */

public class ReadFile_By_byte {

  

//注:FileInputStream是按照一個字節一個字節的讀取數據的,由於一箇中文是二個字節,因此讀取中文的時候會出現亂碼

public void ReadFile(String path) throws IOException{

 //加載文件

File  F=new File(path);

FileInputStream fis=null;

int count=0;

int sum=0;

 

//建立文件讀取流

try {

fis=new FileInputStream(F);

while((count=fis.read())!=-1){

System.out.println((char)count);

sum++;

}

} catch (FileNotFoundException e) {

 

e.printStackTrace();

}finally{

 

if(fis!=null){

fis.close();

}

}

}

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

ReadFile_By_byte rb=new ReadFile_By_byte();

rb.ReadFile("E:/filezl.txt");

}

}

四:使用BufferReader讀取中文代碼以下:

package com.javaIo;

 

import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

 

/**

 * @使用FileBufferReader讀取中文

 * @author zl

 *

 */

public class ReadFile_By_BufferRead {

  

public  static void   readFile(String path) throws IOException{

FileReader Fr=null;

BufferedReader br=null;

String content="";

try {

Fr=new FileReader(path);

br=new BufferedReader(Fr);

while((content=br.readLine())!=null){

System.out.println(content);

}

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

br.close();

Fr.close();

}

System.out.println(content);

}

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

ReadFile_By_BufferRead.readFile("E:/filezl.txt");

}

}

相關文章
相關標籤/搜索