posts - 1,  comments - 25,  trackbacks - 0




对于我们常用的GBK中,英文是占用1个字节,中文是2个

  对于UTF-8,英文是1个,中文是3个

  对于Unicode,英文中文都是2个

  Java的流操作分为字节流和字符流两种。

2.3 Java 中相关实现方法

字符串类 String 中的内容是 UNICODE 字符串:

// Java 代码,直接写中文
String
 string = "中文123";

// 得到长度为 5,因为是 5 个字符
System.out.println(string.length());

字符串 I/O 操作,字符与字节转换操作。在 Java 包 java.io.* 中,以“Stream”结尾的类一般是用来操作“字节串”的类,以“Reader”,“Writer”结尾的类一般是用来操作“字符串”的类。

// 字符串与字节串间相互转化

// 按照 GB2312 得到字节(得到多字节字符串)

byte
 [] bytes = string.getBytes("GB2312");

// 从字节按照 GB2312 得到 UNICODE 字符串
string = new String(bytes, "GB2312");

// 要将 String 按照某种编码写入文本文件,有两种方法:

// 第一种办法:用 Stream 类写入已经按照指定编码转化好的字节串

OutputStream os = new FileOutputStream("1.txt");
os.write(bytes);
os.close();

// 第二种办法:构造指定编码的 Writer 来写入字符串
Writer ow = new OutputStreamWriter(new FileOutputStream("2.txt"), "GB2312");
ow.write(string);
ow.close();

/* 最后得到的 1.txt 和 2.txt 都是 7 个字节 */

如果 java 的源程序编码与当前默认 ANSI 编码不符,则在编译的时候,需要指明一下源程序的编码。比如:

E:\>javac -encoding BIG5 Hello.java

以上需要注意区分源程序的编码与 I/O 操作的编码,前者是在编译时起作用,后者是在运行时起作用。

IO分两种流 

字节流 InputStream OutputStream 

字符流 Reader Writer 

他们都是抽象类 

具体实现 
字节流 FileInputStream FileOutputStream 
字符流 FileReader FileWriter  

       字符流处理的单元为2个字节的Unicode字符,分别操作字符、字符数组或字符串,而字节流处理单元为1个字节, 操作字节和字节数组。所以字符流是由Java虚拟机将字节转化为2个字节的Unicode字符为单位的字符而成的,所以它对多国语言支持性比较好!如果是 音频文件、图片、歌曲,就用字节流好点,如果是关系到中文(文本)的,用字符流好点. 
     所有文件的储存是都是字节(byte)的储存,在磁盘上保留的并不是文件的字符而是先把字符编码成字节,再储存这些字节到磁盘。在读取文件(特别是文本文件)时,也是一个字节一个字节地读取以形成字节序列. 
      字节流可用于任何类型的对象,包括二进制对象,而字符流只能处理字符或者字符串; 2. 字节流提供了处理任何类型的IO操作的功能,但它不能直接处理Unicode字符,而字符流就可以。 


字节流转换成字符流可以用 InputSteamReader OutputStreamWriter 

转换成BufferdReader BufferedWriter 他们具有缓冲区 

例如:读取文件 从字节流输入到字符流输入 
定义一个字节流: 
FileInputStream fileInputStream = new FileInputStream("d:/text.txt"); // 定义一个指 

向D:/TEXT.TXT 的字节流 

InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); 
//字节流转换成InputStreamReader 
BufferedReader bufferedReader = new BufferedReader(inputSteamReader); 
//InputStreamReader 转换成带缓存的bufferedReader 

可以把读出来的内容赋值给字符 

String ss = new String(); 
String s; 
while((s = bufferedReader.readLine())!=null){ 
ss += s; 


例如:写入文件 从字节流输出到字符流输出 

FileOutputStream fileOutputStream = new FileOutputStream("d:/text.txt"); //定义一个 

指向D:/TEXT.TXT文件 

OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); 

BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); 

bufferedWriter.write(s); 

bufferedWriter.close(); 
outputStreamWriter.close(); 
fileOutputStream.close(); 


例程: 
     将字符串转化为字节流#region 将字符串转化为字节流 
        /**//// <summary> 
        /// 将字符串转化为字节流 
        /// </summary> 
        /// <param name="_Source">字串</param> 
        /// <returns>字节流</returns> 
        public static byte[] String2Bytes(string strSource) 
        { 
            System.IO.MemoryStream   memoryStream=new   System.IO.MemoryStream();   
            System.IO.BinaryWriter   binaryWriter=new   System.IO.BinaryWriter(memoryStream);   
            binaryWriter.Write( strSource ); 
            byte[]   buffer=memoryStream.GetBuffer(); 
            return buffer;    
        } 
        #endregion 

        
        将字节流转化为字符串#region 将字节流转化为字符串 
        /**//// <summary> 
        /// 将字节流转化为字符串 
        /// </summary> 
        /// <param name="bytData">字节流</param> 
        /// <returns>字串</returns> 
        public static string Bytes2String(byte[] bytData) 
        { 
            //字节流->字符串   
            System.IO.MemoryStream   memoryStream2 = new   System.IO.MemoryStream(bytData);   
            System.IO.BinaryReader   binaryReader = new   System.IO.BinaryReader(memoryStream2);   
            string   s2=binaryReader.ReadString();   
            return s2; 
        } 
        #endregion
posted on 2010-08-16 17:16 Daniel 阅读(1774) 评论(1)  编辑  收藏 所属分类: CoreJava

FeedBack:
# re: Java的字符流和字节流
2011-12-23 20:39 | mlzry0612
留下备忘!
文件拷贝:
Java代码
public static void copyFile(File src,File dest) throws Exception{
try {
// Create channel on the source
FileChannel srcChannel = new FileInputStream(src).getChannel();

// Create channel on the destination
FileChannel dstChannel = new FileOutputStream(dest).getChannel();

// Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

// Close the channels
srcChannel.close();
dstChannel.close();
} catch (IOException e) {
}

}

文件重命名:
Java代码
public static renameFile(File src,String newFilename)throws Exception{
src.renameTo(new File(newFilename));//请写明完整路径
}

将文件读成字符串:
Java代码
public static String ReadFileToString(String pathAndFilename) {
StringBuffer str = new StringBuffer();
BufferedReader in = null;
File inputFile = null;
try {
inputFile = new File(pathAndFilename);
in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "utf-8"));
String line = null;
str = new StringBuffer((int) inputFile.length());
while ((line = in.readLine()) != null) {
str.append(line);
}
in.close();
}
catch (FileNotFoundException e2) {
try {
if (!new File(inputFile.getParent()).exists())
new File(inputFile.getParent()).mkdirs();
inputFile.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
}
catch (IOException e3) {
e3.printStackTrace();
}
return str.toString();
}   回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

常用链接

留言簿(3)

随笔档案

文章分类

文章档案

相册

搜索

  •  

最新评论