Scanner类和字符编码详解

来源:互联网 发布:c语言小游戏代码txt 编辑:程序博客网 时间:2024/06/10 07:38

Scanner是一个新的操作类,是在java.util包中提供的一个操作类,使用此类可以方便的完成输入流的输入操作。

使用此类也可以进行正则匹配,例如:输入日期格式:

package com.demo.io;import java.util.Scanner;public class ScannerDemo {public static void main(String args[]){Scanner scanner = new Scanner(System.in);String str = null;if(scanner.hasNext("\\d{4}/\\d{2}/\\d{2}")){//如果输入的是日期格式str = scanner.next();}System.out.println("result= "+str);}}//结果//输入://2012/07/26//result= 2012/07/26

因为此类接收的是输入流的操作类,所以也可以使用此类完成文件内容的读取。

package com.demo.io;import java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;public class ScannerDemo {public static void main(String args[]) throws FileNotFoundException{Scanner scanner = new Scanner(new File("g:"+File.separator+"demo.txt"));StringBuffer stringBuffer = new StringBuffer();//表示以\n为换行符scanner.useDelimiter("\n");while(scanner.hasNext()){stringBuffer = stringBuffer.append(scanner.next());}System.out.println("result= "+stringBuffer);}}

字符编码:

在程序中如果字符编码没有处理完整,则肯定会造成乱码,常见的编码有以下几种:

*UTF:包含以下的编码
*ISO 8859-1:是包含全部的英文的编码

*GBK/GB2312:表示中午,GBK表示简体中文和繁体中文、GB2312只表示简体中文。

如果程序中操作的编码与本地的环境编码不统一,那么操作的时候就有可能出现乱码。

范例:观察本机的系统编码

package com.demo.io;public class CharEnCoding {public static void main(String args[]){//获得本机系统信息System.getProperties().list(System.out);}}



所以,在操作的时候默认的编码就是GBK,如果要在程序中使用的时候,则使用的编码也应该是GBK,那么如果此时使用了ISO8859-1的话,则就有可能出现乱码。

package com.demo.io;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;public class CharEnCoding {public static void main(String args[]) throws IOException{OutputStream outputStream = new FileOutputStream("g:"+File.separator+"encodDemo.txt");String demoStr = "这是一个字符编码操作的例子";//本机编码环境是GBK 这里为了演示我们设置成ISO8859-1outputStream.write(demoStr.getBytes("ISO8859-1"));outputStream.close();}}
乱码造成的根本原因就在于程序与本机环境的编码不统一。