------- android培训、java培训 、期待与您交流! ----------
System类包含一些有用的类字段和方法。它不能被实例化
获取系统属性例子:
Class SystemDemo{
Public static void main(String args[]){
Properties prop = System.getProperties();
For(Object obj : prop.keySet()){
String value = (String)prop.get(obj);
System.out.println(obj+”::”+value);
}}}
设置属性值:
System.setProperty(“mykey”,”myvalue”);
获取指定属性信息:
String value = System.getProperty(“os.name”);
可以动态地添加一些属性值:
在运行时
Java –D<name>=value SystemDemo
类Runtime
每个java应用程序都有一个Runtime类实例,使应用程序能够与其运行的环境相连接。可以通过getRuntime方法获取当前运行时。应用程序不能创建自己的Runtime类实例。
该类没有构造方法,正常来说如果没有构造方法则它的方法必须都是静态的,但Runtime类却又非静态方法,说明此类的对象我们可以通过某方法调用,即getRuntime()方法,返回Runtime类对象。
例如:
Class RuntimeDemo{
Public static void main(String args[]){
Runtime r = Runtime.getRuntime();
r.exec(“c:\\winmine.exe”); //执行命令的方法,传递一个命令进去即可,此处是让它打开c盘下的扫雷程序。
}
}
Process p = r.exec(“winmine.exe”); //该方法返回一个进程
p.destroy(); //销毁一个进程
Process p = r.exec(“notepad.exe SystemDemo.java”); //打开一个记事本并且记事本的内容显示SystemDemo.java的内容。只要程序能找到此文件的路径就能打开。
Date类
Class DateDemo{
Public static void main(String[] args){
Date d = new Date();
System.out.println(d); //获取当前时间
}
}
规定日期格式:
Date d = new Date();
//将模式封装到SimpleDateformat对象中
SimpleDateFormate sdf = new SimpleDateFormate(“yyyy年MM月dd日 E hh:mm:ss”);//E代表星期几
//调用format方法让模式格式化指定Date对象
String time = sdf.format(d);
System.out.println(“time=”+time);
Calendar类:
Class CalendarDemo{
Public static void main(String args[]){
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.YEAR)+“年”);
System.out.println(c.get(Calendar.MONTH)+“月”);
System.out.println(c.get(Calendar.DAY_OF_MONTH)+“日”);
//但此处的月是从0开始的要想正常显示必须加1.而且还不能用汉字的月份来表示
}
}
所以我们有另外一种表达月数的方法
String mons[] = {“一月”,”二月” ,”三月” ,”四月” ,”五月” ,”六月” ,”七月” ,”八月” ,”九月” ,”十月” ,”十一月” ,”十二月”};
Int index = c.get(Calendar.MONTH);
System.out.println(mons[index]);
还可以使用Calendar类来设置日期:
Calendar c = Calendar.getInstance();
c.get(2012,2,23); //这里的2其实代表的是三月。
c.add(字段名,偏移量)
c.add(Calendar.YEAR,4); //现有年份加四
Math类:
Math.ceil() //向上取整
Math.floor() //向下取整
Math.round() //加0.5后再向下取整
Math.pow(2,3); //返回2的3次幂
产生随机数:
Int d = (int)(Math.random()*10+1); //产生1-10的随机整数
Math.random() //产生0-1的随机数,包含0不包含1
也可以使用Random类
nextInt(int n)返回下一个伪随机数,它是取自此随机数生成器序列的在0(包括)和指定值(不包括)之间均匀分布的int值。
Random r = new Random();
Int d = r.nextInt(10)+1
IO流常用基类
字节流的抽象基类:InputStream,OutputStream
字符流的抽象基类:Reader,Writer
注:由这四个类派生出来的子类名称都是以其父类名作为子类名的后缀。
如:InputStream的子类FileInputStream
如:Reader的子类FileReader
Class FileWriterDemo{
Public static void main(String args[]){
FileWriter fw = new FileWriter(“demo.txt”);
//调用write方法,将字符串写入到流中
Fw.write(“abcde”); //此时demo.txt中并没有数据
//刷新流对象中的缓冲中的数据,将数据刷到目的地
//Fw.flush(); //此时demo.txt中开始有数据
//或直接调用关闭函数,关闭流资源,但是关闭之前会刷新一次内部的缓冲中的数据。
Fw.close();
}
}
对已有文件的数据续写
FileWriter fw = new FileWriter(“demo.txt”,true);
Fw.write(“nihao\r\nxiexie”); //这里的\r\n代表换行的意思
Fw.close();
字符的读取流对象:
FileReader fr = new FileReader(“demo.txt”);
While(true){
Int ch = fr.read();
If(ch==-1)
Break;
System.out.println(“ch=”+(char)ch);
}
或者是:
Int ch = 0;
While((ch = fr.read())!=-1){
System.out.println((char)ch);
}
读取字符数组:
Char[] buf = new char[3];
Int num = 0;
While(num=fr.read(buf)!=-1){
System.out.println(new String(buf,0,num));
}
复制文件:
读一个字符,写一个字符
FileWriter fw = new FileWriter(“RuntimeDemo_copy.txt”);
FileReader fr = new FileReader(“RuntimeDemo.java”);
Int ch = 0;
While((ch=fr.read())!=-1){
Fw.write(ch);
}
Fw.close();
Fr.close();
全部读完后再写:
Public static void copy_2(){
FileWriter fw = null;
FileReader fr = null;
Try{
Fw = new FileWriter(“SystemDemo.txt”);
Fr = new FileReader(“SystemDemo.java”);
Char[] buf = new char[1024];
Int len = 0;
While(len = fr.read(buf)!=-1){
Fw.write(buf,0,len);
}
}
Catch(IOException e){
Trhow new RuntimeException(“读写失败”);
}
}
字符的缓冲区:
FileWriter fw = new FileWriter(“buf.txt”);
BufferedWrtier bufw = new BufferedWriter(fw);
Bufw.write(“abcde”);
Bufw.flush();
//其实关闭缓冲区,就是关闭缓冲区中的流对象,所以fw.close()就不需要了。
Bufw.close();
Bufw.newLine(); //换行函数,此方法是跨平台的即在linux和window里都能用。
FileReader fr = new FileReader(“buf.txt”);
BufferedReader bufr = new BufferedReader(fr);
String line = null;
While((line = bufr.readLine())!=null){
System.out.println(line);
}
复制文件:
BufferedReader bufr = null;
BufferedWriter bufw = null;
Try{
Bufr = new BufferedReader(new FileReader(“a.java”));
Bufw = new BufferedWriter(new FileWriter(“b.java”));
String line = null;
While((line=bufr.readline())!=null){
Bufw.write(line);
Burw.newLine();
Bufw.flush();
}
}
了解了BufferedReader类中特有方法readLine的原理后,可以自定义一个类中包含一个功能和readLine一致的方法。
Class MyBufferedReader{
Private FileReader r;
MyBufferedReader(FileReader r){
This.r = r;
}
Public String myReadLine(){
StringBuilder sb = new StringBuilder();
Int ch = 0;
While((ch=r.read()!=-1)){
If(ch==’\r’)
Continue;
If(ch==’\n’)
Return sb.toString();
Else
Sb.append((char)ch);
}
Return null;
}
Public void myClose(){
r.close();
}
}
装饰设计模式:
当想要对已有的对象进行功能增强时,可以定义类,将已有对象传入,基于已有的功能,并提供加强功能。那么自定义的该类称为装饰类。
装饰类通常会通过构造方法接收被装饰的对象。并基于被装饰的对象的功能,提供更强的功能。
例如对已有的person类进行装饰:
Class Person{
Public void chifan(){
System.out.println(“吃饭”);
}
}
Class SuperPerson{
Private Person p;
SuperPerson(Person p){
This..p = p ;
}
Public void superChifan(){
System.out.println(“开胃酒”);
p.chifan();
System.out.println(“甜点”);
System.out.println(“散步”);
}
}
Public class PersonDemo{
Public static void main(String args[]){
SuperPerson sp = new SuperPerson();
Sp.superChifan();
}
}
BufferedReader的子类LineNumberReader功能基本同父类一样只是多了个设置行号的功能。
Class LineNumberReaderDemo{
Public static void main(String args[]) throws IOException{
FileReader fr = new FileReader(“PersonDemo.java”);
LineNumberReader lnr = new LineNumberReader(fr);
String line = null;
Lnr.setLineNumber(100);
While((line = lnr.readLine())!=null){
System.out.println(lnr.getLineNumber()+”:”+line);
}
Lnr.close();
}
}
字节流
写文件字符流:
FileOutputStream fos = new FileOutputStream(“fos.txt”);
Fos.write(“abcde”.getBytes());
读字符流:
一个一个读:
FileInputStream fis = new FileInputStream(“fos.txt”);
Int ch = 0;
While((ch=fis.read())!=-1){
System.out.println((char)ch);
}
Fis.close();
先读到数组里再打印:
FileInputStream fis = new FileInputStream(“fos.txt”);
Byte[] buf = new byte[1024];
Int len = 0;
While((len = fis.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
Fis.close();
Available()函数获取文件的大小:
FileInputStream fis = new FileInputStream(“fos.txt”);
Byte[] buf = new byte[fis.avilable()]; //把数组的大小定义成刚刚好
Fis.read(buf);
System.out.println(new String(buf));
Fis.close();
复制图片:
Class CopyPic{
Public static void main(String args[]){
FileOutputStream fos = null;
FileInputStream fis = null;
Try{
Fos = new FileOutputStram(“c:\\2.bmp”);
Fis = new FileInputStream(“c:\\1.bmp”);
Byte[] buf = new byte[1024];
Int len = 0;
While((len=fis.read(buf))!=-1){
Fos.write(buf,0,len);
}
}catch(Excetption e){
Throw new RuntimeException(“复制文件失败”);
}
Finally{
Try{
If(fis!=null)
Fis.close();
}catch(IOException e){
Throw new RuntimeException(“读取关闭失败!!”);
}
}
Finally{
Try{
If(fos!=null)
Fos.close();
}catch(IOException e){
Throw new RuntimeException(“复制关闭失败!!”);}}}}
通过缓冲区复制mp3文件:
BufferedInputStream bufis = new BufferedInputStream(new FileInputStream(“c:\\0.mp3”));
BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream(“c:\\1.mp3”));
Int by =0;
While((by=bufis.read())!=-1){
Bufos.write(by);
}
Bufos.close();
Bufis.close();
当录入一行数据后,就将该行数据进行打印,如果录入的数据是over,那么停止录入。
Class ReadIn{
Public static void main(String args[]) throws IOException{
InputStream in = System.in;
StringBuilder sb = new StringBuilder();
While(true){
Int ch = in.read();
If(ch==’\r’)
Continue;
If(ch==’\n’){
String s = sb.toString();
If(“over”.equals(s))
Break;
System.out.println(s.toUpperCase());
Sb.delete(0,sb.length);
}
Else
Sb.append((char)ch);}}}
将字节流转换成字符流再使用字符流缓冲区的readLine方法。
Class TransStreamDemo{
Public static void main(String args[]){
InputStream in = System.in;
InpustStreamReader isr = new InpustStreamReader(in);
BufferedReader bufr = new BufferedReader(isr);
String line = null;
While((line=bufr.readLine())!=null){
If(“over”.equals(line))
Break;
System.out.println(line.toUpperCase());
}
Bufr.close();
}
}
写入转换流:
OutputStream out = System.out;
OutputStreamWriter osw = new OutputStreamWriter(out);
BufferedWriter bufw = new BufferedWriter(osw);
String line = null;
While((line=bufr.readLine())!=null){
If(“over”.equals(line))
Break;
bufw.write(line.toUpperCase());
bufw.newLine();
bufw.flush();
}
Bufr.close();
键盘录入的方法:
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
扩展一下,想要把录入的数据按照指定的编码表(utf-8),将数据存到文件中。
目的:OutputStream Writer
是否是纯文本?是!Writer
设备:硬盘。一个文件。使用FileWriter
但是FileWriter是使用的默认编码表。GBK
但是存储是,需要加入指定编码表utf-8.而指定的编码表只有转换流可以指定。
所以要使用的对象是OutputStreamWriter。
而该转换流对象要接收一个字节输出流,而且还可以操作的文件的字节输出流。FileOutputStream
需要高效吗?需要
BufferedWriter bufw = new BufferedWriter(osw);
设置源和目的:
System.setIn(new FileInputStream(“PersonDemo.java”));
System.setOut(new PrintStream(“zzz.txt”));
将系统的属性信息打印出来
Properties prop =System.getProperties();
//Prop.list(new PrintStream(“sysinfo.txt”));
Prop.list(System.out);
File类常见方法:
Boolean creatNewFile():在指定位置创建文件,如果该文件已经存在,则吧创建,返回false。和输出流不一样,输出流对象一建立创建文件。而且文件已经存在,会覆盖。
删除:
Boolean delete():删除失败返回false
Void deleteOnExit();在程序退出时删除指定文件。
Boolean mkdir():创建文件夹
File dir = new File(“abc”); 或File dir = new File(“abc\\kkk”); //mkdir()只能创建一级目录。
Sop(“mkdir:”+dir.mkdir());
Boolean mkdirs():创建多级文件夹
isHidden() //是否为隐藏文件
isAbsolutePath() //是否是绝对路径
获取信息的方法:
getName();
getPath();
getParent(); // 该方法返回的是绝对路径中的父目录。如果获取的是相对路劲,返回null.如果相对路径中有上一层目录那么该目录就是返回结果。
getAbsolutePath()
lastModified() //最后一次修改的时间
length()
File f1 = new File(“c:\\Test.java”);
File f2 = new File(“c:\\hahah.java”);
F1.renameTo(f2); //把f1改成f2 也可以实现复制粘贴的功能
listRoots()返回电脑里的盘符。如c盘、d盘等
File f = new File(“c:\\”);
String[] names = f.list();
For(String name:names){
System.out.println(name); //列出c盘下的文件及文件夹并打印。
} //调用list方法的file对象必须是封装了一个目录,该目录还必须存在。
过滤文件:
File dir = new File(“d:\\java1223\\day18”);
String[] arr = dir.list(new FilenameFilter()
{
Public Boolean accept(File dir,String name){
/*
If(name.endsWith(“.bmp”)) //过滤出.bmp文件
Return true;
Else
Return false;
*/
Return name.endsWith(“.bmp”);
}
}
);
ListFiles()方法:
File dir = new File(“c:\\”);
File[] files = dir.listFiles();
For(file f: files){
System.out.println(f.getName()+”::”+f.length());
}
删除一个带内容的目录:
删除原理:
在window中,删除目录从里面往外删除的,既然是从里往外删除,就需要用到递归。
Public static void removeDir(File dir){
File files = dir.listFiles();
For(int x=0;x<files.length;x++){
If(!files[x].isHidden()&&files[x].isDirectory())
removeDir(files[x]);
else
System.out.println(file[x].toString()+”::”+files.delete())
}
}
练习:将一个指定目录下的java文件的绝对路径,存储到一个文本文件中。建立一个java文件列表文件。
Class JavaFileList{
Public static void main(String[] args) throws IOException{
File dir = new File(“d:\\java1223”);
List<File> list = new ArrayList<File>();
fileToList(dir,list);
writeToFile(list);
}
Public static void fileToList(File dir,List<File> list){
File[] files = dir.listFiles();
For(File file:files){
If(file.isDirectory ())
fileToList(file,list);
else{
if(file.getName().endsWith(“.java”))
list.add(file);
}
}
}
Public static void writeToFile(List<File> list,String javaListFile) throw IOException{
BufferedWriter bufw = null;
Try{
Bufw = new BufferedWriter(new FileWriter(javaListFile));
For(File f:list){
String path = f.getAbsolutePath();
Bufw.write(path);
Bufw.newLine();
Bufw.flush();
}
}
Catch(IOException e){
Throw e;
}
Finally{
Try{
If(bufw!=null)
Bufw.close();
}catch(IOException e){
Throw e;
}
}
}}
Properties是hashtable的子类,也就是说它具备map集合的特点,而且它里面存储的键值对都是字符串,是集合和IO技术相结合的集合容器。该对象的特点,可以用于键值对形式的配置文件。
Public static void setAndGet(){
Properties prop = new Properties();
Prop.setProperty(“zhangsan”,”30”);
Prop.setProperty(“lisi”,”39”);
//System.out.println(prop);//打印的结果为<zhangsan=30,lisi=39>
Prop.setProperty(“lisi”,89+””); //修改已有属性的值同上边的形式一样。
Set<String> names = prop.stringPropertyName(); //JDK1.6后才有
For(String s:names){
System.out.println(s+”:”+prop.getProperty(s));
}
}
想要将info.txt中键值数据存到集合中进行操作:
1. 用一个流和info.txt文件关联
2. 读取一行数据,将该行数据用”=”进行切割
3. 等号左边作为键,右边作为值,存入到Properties集合中即可。
Public static void method_1() throws IOException{
BufferedReader bufr = new BufferedReader(new FileReader(info.txt));
String line = null;
Properties prop = new Properties();
While((line=bufr.readline())!=null){
String[] arr = line.split(“=”);
//System.out.println(arr[0]+”….”+arr[1]);
Prop.setProperty(arr[0],arr[1]);
}
Bufr.close();
System.out.println(prop);
}
Properties对象提供了load()方法可以直接传入输入流,不必写的向上边那么复杂。
Public static void loadDemo() throws IOException{
Properties prop = new Properties();
FileInputStream fis = new FileInputStream(“info.txt”);
//将流中的数据加载进集合
Prop.load(fis);
//System.out.println(prop); //功能同上述一样
Prop.list(System.out); //同上述功能一样
Prop.setProperty(“wangwu”,39); //此时只是修改的内存的值但文件里的内容并为改变
FileoutputStream fos = new FileOutputStream(“info.txt”);
Prop.store(fos,”haha”);
//System.out.println(prop);
Prop.list(System.out);
Fos.close();
Fis.close();
}
用于记录应用程序运行次数
如果使用次数已到,那么给出注册提示。
很容易想到的是:计数器。
可是该计数器定义在程序中,随着程序的运行而在内存中存在,并进行自增。
可是随着该应用程序的退出,该计数器也在内存中消失了。
下一次在启动该程序,又重新开始从0计数
这样不是我们想要的。
程序即使结束,该计数器的值也存在。
下次程序启动在会先加载该计数器的值并加1后再重新存储起来。
Public static void main(String[] args) throws IOException{
Properties prop = new Properties();
File file = new File(“count.ini”);
If(!file.exists())
File.createNewFile();
FileInputStream fis = new FileInputStream(file);
Prop.load(fis);
Int count=0;
String value = prop.getProperty(“time”);
If(value!=null){
Count = Integer.parseInt(value);
If(count>=5){
System.out.println(“已到期请交费”);
}
}
Count++;
Prop.setProperty(“time”,count+””);
FileOutputStream fos = new FileOutputStream(file);
Prop.store(fos,””);
Fos.close();
Fis.close();
}
打印流:
该流提供了打印方法,可以将各种数据类型的数据都原样打印
字节打印流:
PrintStream构造函数可以接受的参数类型:
1. file对象。File
2. 字符串路径。String
3. 字节输出流。OutputStream
字符打印流;
PrintWriter构造函数可以接受的参数类型:
1file对象。File
2字符串路径。String
3字节输出流。OutputStream
4.字符输出流。Writer
Class PrintStreamDemo{
Public static void main(String[] args){
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new FileWriter(“a.txt”),true); //自动刷新
String line = null;
While((line=bufr.readLine())!=null){
If(“over”.equals(line))
Break;
Out.println(line.toUpperCase());
}
Out.close();
Bufr.close();
}
}
把多个文件合并成一个文件:
Class SequenceDemo{
Public static void main(String[] args){
Vector<FileInputStream> v = new Vector<FileInputStream>();
v.add(new FileInputStream(“c:\\1.txt”));
v.add(new FileInputStream(“c:\\2.txt”));
v.add(new FileInputStream(“c:\\3.txt”));
Enumeration<FileInputStream> en = v.elements();
SequenceInputStream sis = new SequenceInputStream(en);
FileOutputStream fos = new FileOutputStream(“c:\\4.txt”);
Byte[] buf = new byte[1024];
Int len =0;
While((len=sis.read(buf))!=-1){
Fos.write(buf,0,len);
}
Fos.close();
Sis.close();
}
}
把一个文件分割成多个文件:
Public static void splitFile(){
FileInputStream fis = new FileInputStream(“c:\\1.bmp”);
FileOutputStream fos = null;
Byte[] buf = new byte[1024*1024];
Int len =0;
Int count =0;
While((len=fis.read(buf))!=-1){
Fos = new FileOutputStream(“c:\\splitfiles\\”+(count++)+”.part”);
Fos.write(buf,0,len);
Fos.close();
}
Fis.close();
}
合并文件;
Public static void merge(){
ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
For(int x=1;x<=3;x++){
Al.add(new FileInputStream(“c:\\splitfiles\\”+x+”.part”));
}
Final Iterator<FileInputStream> it = al.iterator();
Enumeration<FileInputStream> en = new Enumeration<FileInputStream>(){
Public Boolean hasMoreElements(){
Return it.hasNext();
}
Public FileInputStream nextElement(){
Return it.next();
}
}
SequenceInputStream sis = new SequenceInputStream(en);
FileOutputStream fos = new FileOutputStream(“c:\\splitfiles\\0.bmp”);
Byte[] buf = new byte[1024];
Int len =0;
While{
Fos.write(buf,0,len);
}
Fos.close();
Sis.close();
}
操作对象:
ObjectInputStream与ObjectOutputStream //被操作的对象需要实现Serializable(标记接口)
程序中产生的对象不是存在内存的堆内存中而是存在文件中。
Public static void writeObj() throws IOException{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(“obj.txtt”));
Oos.writeobjectt(new Person(“lisi”,39)); //person对象必须实现Serializable接口。
}
从文件里读出对象信息;
Public static void readObj() throws IOException{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(“obj.txt”));
Person p = (Person)ois.readObject();
System.out.println(p);
Ois.close();
}
此时的程序如果person类被修改了则不能用了,如果想要修改Person的属性而还能从文件里读出对象的内容,则需要在Person类里加一句话:public static final long serialVersionUID=42l自己定义一个UID就行了。
静态变量不能被序列化。如果Person类里有不想被序列化的属性则用transient修饰,即用transient修饰的属性不能序列化。
管道流:PipedInputStream和PipedOutStream输入输出可以直接进行连接,通过结合线程使用。
Class Read implements Runnable{
Private PipedInputStream in;
Read(PipedInputStream in){
This.in = in ;
}
Public void run(){
Try{
Byte[] buf = new byte[1024];
Int len = in.read(buf);
String s = new String(buf,0,len);
System.out.println(s);
In.close();
}catch(){
Throw new RuntimeException(“管道读取流失败”);
}
}
}
Class Write implements Runnable{
Private PipedOutputStream out;
Write(PipedOutputStream out){
This.out = out;
}
Public void run(){
Try{
Out.write(“piped lai la”.getBytes());
Out.close();
}catch(){
Throw new RuntimeException(“管道输出流失败”);
}
}
}
RandomAccessFile类
Public static void writeFile() throws IOException{
RandomAccessFile raf = new RandomAccessFile(“ran.txt”,rw);
Raf.write(“李四”.getBytes());
Raf.writeInt(97);
Raf.close();
}
Public static void readFile() throws IOException{
RandomAccessFile raf = new RandomAccessFile(“ran.txt”,”r”);
//Raf.seek(8);
//跳过指定的字节数
Raf.skipBytes(8); //跳过指定的位数,不能往回跳只能往后跳。
Byte[] buf = new byte[4];
Raf.read(buf);
String name = new String(buf);
Int age = raf.readInt();
System.out.println(“name”+name);
System.out.println(“age”+age);
Raf.close();
}
如果模式为只读r,不会创建文件,会去读取一个已存在文件,如果该文件不存在,则会出现异常。如果模式为rw,操作的文件存在,会自动创建,如果存在则不会覆盖。
DataInputStream与DataOutputStream:可以用于操作基本数据类型的数据的流对象。
Public static void writeData() throws IOException{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(“data.txt”));
Dos.writeInt(234);
Dos.writeBoolean(true);
Dos.writeDouble(9887. 543);
Dos.close();
}
Public static void readData(){
DataInputStream dis = new DataInputStream(new FileInputStram(“data.txt”));
Int num= dis.readInt();
Boolean b = dis.readBoolean();
Double d = dis.readDouble();
System.out.println(“num=”+num);
System.out.println(“b=”+b);
System.out.println(“d=”+d);
Dis.close();
}
Public static void writeUTFDemo() throws IOException{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(“utfdata.txt”));
Dos.writeUTF(“你好”);
Dos.close();
}
Public static void readUTFDemo() throws IOException{
DataInputStream dis = new DataInputStream(new FileInputStream(utf.txt));
String s= dis.readUTF();
System.out.println(s);
Dis.close();
}
用于操作字节数组的流对象:
ByteArrayInputStream:在构造的时候,需要接受数据源,而且数据源是一个字节数组。
ByteArrayOutputStream:在构造的时候,不用定义数据目的,因为该对象中已经内部封装了可变长度的字节数组。
因为这两个流对象都操作的数组,并没有使用系统资源。所以不用进行close关闭。
Class ByteArrayStream{
Public static void main(String args[]){
ByteArrayInputStream bis = new ByteArrayInputStream(“ABCDEFG”.getBytes());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Int by =0;
While((by-bis.read())!=-1){
Bos.write(by);
}
System.out.println(bos.size());
System.out.println(bos.toString());
//bos.writeTo(new FileOutputStream(“a.txt”)); //把内容写到一个文件里
}
}
常见编码表:
ASCII:美国标准信息交换码,用一个字节的7位可以表示。
ISO8859-1:拉丁码表,欧洲码表,用一个字节的8位表示。
GB2312:中国的中文编码表
GBK:中国的中文编码表升级,融合了更多的中文文字符号。
Unicode:国际标准码,融合了多种文字,所有文字都用两个字节来表示,java语言使用的就是unicode
UTF-8:最多用三个字节来表示一个字符。
Public static void writeText() throws IOException{
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(“utf.txt”),”UTF-8”);
Osw.write(“你好”);
Osw.close();
}
Public static void readText() throws IOException{
InputStreamReader isr = new InputStreamReader(new FileInputStream(“utf.txt”),”gbk”);
Char[] buf = new char[10];
Int len = isr.read(buf);
String str = new String(buf,0,len);
System.out.println(str);
Isr.close();
}
编码:字符串变成字节数组。
解码:字节数组变成字符串。
Stringàbyte[];str.getBytes(charsetName);
Byte[]àString:new String(byte[],charsetName);
Class EncodeDemo{
Public static void main(String[] args) throws Exception{
String s = “你好”;
Byte[] b1 = s.getBytes(“UTF-8”);
System.out.println(Arrays.toString(b1));
String s1 = new String(b1,”UTF-8”);
System.out.println(“s1=”+s1);
}
}
例题:有五个学生,每个学生有3门课的成绩,从键盘输入以上数据(包括姓名,三门课成绩),输入的格式:如:zhangsan,30,40,60计算出总成绩,并把学生的信息和计算出的总分数按高低顺序存放在磁盘文件”stud.txt”中。
1. 描述学生对象。
2. 定义一个可操作学生对象的工具类。
思想:
1. 通过获取键盘录入一行数据,并将该行中的信息取出封装成学生对象。
2. 因为学生有很多,那么就需要存储,使用到集合,因为要对学生的总分排序。所以可以使用TreeSet。
3. 将集合的信息写入到一个文件中。
Class Student implements Comparable<Student>{
Private String name;
Private int ma,cn,en;
Private int sum;
Student(String name,int ma,int cn,int en){
This.name = name;
This.ma = ma;
This.cn = cn;
This.en = en ;
Sum = ma+cn+en;
}
Public int compareTo(Student s){
Int num = new Integer(this.sum).compareTo(new Integer(s.sum));
If(num==0)
Return this.name.compareTo(s.name);
Return num;
}
Public String getName(){
Return name;
}
Public int getSum(){
Return sum;
}
Public int hashCode(){
Return name.hashCode()+sum*78;
}
Public Boolean equals(Object obj){
If(!(obj instanceof Student))
Throw new ClassCastException(“类型不匹配”);
Student s = (Student)obj;
Return this.name.equals(s.name)&&this.sum==s.sum;
}
Public String toString(){
Return “Student[“+name+”,”+ma+”,”+cn+”,”+en+”]”
}
}
Class StudentInfo{
Public static Set<Student> getStudents() throws IOException{
Return getStudents(null);
}
Public static Set<Student> getStudents(Comparator<Student> cmp) throws IOException{
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
String line = null;
Set<Student> stus = null;
If(cmp==null)
Stus=new TreeSet<Student>();
Else
Stus=new TreeSet<Student>(cmp);
While((line=bufr.readLine())!=null){
If(“over”.equals(line))
Break;
String[] info = line.split(“,”);
Student stu = new Student(info[0],Integer.parseInt(info[1]), Integer.parseInt(info[2]), Integer.parseInt(info[3]));
Stus.add(stu);
}
}
Public static void write2File(Set<Student> stus) throws IOException{
BufferedWriter bufw = new BufferedWriter(new FileWriter(“stuinfo.txt”));
For(Student stu:stus){
Bufw.write(stu.toString()+”\t”);
Bufw.write(stu.getSum()+” ”);
Bufw.newLine();
Bufw.flush();
}
Bufw.close();
}
}
Class StudentInfoTest{
Public static void main(String args[]) throws IOException{
Comparator<Student> cmp = Collection.reverseOrder();
Set<Student> stus = StudentInfoTool.getStudents(cmp);
StudentInfoTool.write2File(stus);
}}