1. PrintWriter()使用示例
package StreamAndFile; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Calendar; import java.util.GregorianCalendar; public class TextFileTest { public static class Employee{ String name; double salary; int year,month,day; public Employee(String name,double salary,int year,int month,int day){ this.name=name; this.salary=salary; this.year=year; this.month=month; this.day=day; } public String getName() { return name; } public double getSalary() { return salary; } public int getYear() { return year; } public int getMonth() { return month; } public int getDay() { return day; } } //将数据写出到文件 public static void writeData(Employee[] staff, PrintWriter out){ for(int i=0;i<staff.length;i++){ out.println(staff[i].getName()+"|"+staff[i].getSalary()+"|"+staff[i].getYear()+ "|"+staff[i].getMonth()+"|"+staff[i].getDay()); } out.flush(); } public static void main(String[] args) { Employee[] staff = new Employee[3]; staff[0]=new Employee("Carl Cracker", 75000, 1987, 12, 15); staff[1]=new Employee("Harry Hacker", 50000, 1989, 10, 1); staff[2]=new Employee("Tony Tester", 40000, 1990, 3, 15); //将数据输出到文件employee.txt中 try { PrintWriter out = new PrintWriter("D:\employee.txt","UTF-8"); writeData(staff,out); System.out.println("写出成功!"); out.close(); } catch (FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } //读入输出的文件中的数据 FileInputStream fis; String str; try { fis = new FileInputStream("D:\employee.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); System.out.println("读出的数据为:"); while((str=br.readLine())!=null){ System.out.println(str); } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
程序运行结果如下:
写出成功! 读出的数据为: Carl Cracker|75000.0|1987|12|15 Harry Hacker|50000.0|1989|10|1 Tony Tester|40000.0|1990|3|15
2. 获得字符集别名及所有可用字符集
获得字符集别名:
package StreamAndFile; import java.nio.charset.Charset; import java.util.Set; //输出字符集的别名 public class GetCharSet { public static void main(String[] args) { Charset cset = Charset.forName("ISO-8859-1"); Set<String> aliases = cset.aliases(); for(String aliase : aliases){ System.out.println(aliase); } } }
程序运行结果如下:
csISOLatin1 latin1 IBM-819 iso-ir-100 8859_1 ISO_8859-1:1987 ISO_8859-1 819 l1 ISO8859-1 IBM819 ISO_8859_1 ISO8859_1 cp819
获得所有可用字符集:
package StreamAndFile; import java.nio.charset.Charset; import java.util.Map; //输出字符集的别名 public class GetCharSet { public static void main(String[] args) {//输出所有可用的字符集的名字 Map<String,Charset> charsets = Charset.availableCharsets(); for(String name:charsets.keySet()){ System.out.println(name); } } }