Java温习篇五

Java复习篇五
从天津转站北京,爬到中关村到直立行走
Java复习篇五
IO流
IO流用于操作数据的,最常见形式是:文件。
字节流的抽象基类:InputStream,OutputStream
字符流的抽象基类:Reader,writer

FileReader创建一个文件读取流对象,和指定名称的文件相关联
对象存放在堆栈内存当中,将堆内存对象存放在硬盘上。
对象的持久化,可序列化。
静态是不能序列化。

源设备:键盘system.in ,硬盘,FileStream,内存ArrayStream
目的设备:控制台System.out,硬盘,FileStream,内存ArrayStream

Node节点:
数据来源(source)——>程序(数据输入流)
数据目的地(sink)<——程序(输出流)

IO包中,字节类别3种节点数
字符类4种节点数

种类、类别 字节 字符
FileInputStream FileReader
文件(file)  FileOutputStream FileWriter
ByteArrayInputStream CharArrayReader
内存(数组) ByteArrayOutputStream CahrArrayWriter
StringReader
内存(字符串) StringWriter

管道(pipe)PipeinputStream pipeReader
pipeOutputStream     PipeWriter

package com.blackhorse.io;
import java.io.*;

/**
*
* @author xinglefly
* @version 1
*/
public class IO1 {
/*
* 将一个文件文本中数据存储到另一个文件中,复制文件。
源:因为是源,所以使用读取流。InputStream Reader
是不是操作文本文件
是!这是可以选择Reader
这样体系就明确了。
接下来明确要使用该体系中的哪个对象。
明确设备:硬盘。上一个文件。
Reader体系中可以操作文件的对象是FileReader.
是否需要提高效率:是!加入Reader体系中缓冲区BufferedReader

FileReader fr = new FileReader("a.txt");
BufferedReader bufr = new BufferedReader(fr);

目的:OutputStream Writer
是否是纯文本。
是,writer.
设备:硬盘,一个文件。Writer体系中更可以操作文件的对象FileWriter.
是否需要提高效率:是!加入Writer体系中缓冲区BufferedWriter
FileWriter fw = new FileWriter("b.txt");
BufferedWriter bufw = new BufferedWriter(fw);
练习:将一个图片文件中数据存储到另一个文件中。复制文件。要按照以上格式自己完成三个明确。
*/


/*
* 1.源:键盘录入:
* 目的:控制台。
* 2.需求:想把键盘录入的数据存储到一个文件中。
* 源:键盘。
* 目的:文件。
*
* 3.需求:想要将一个文件的数据打印在控制台上。
* 源:文件。
* 目的:控制台。
*
* 流操作的基本规律:
* 最痛苦的就是流对象有很多,不知道该用哪一个。
*
* 通过三个明确来完成。
* 1.明确源和目的。
* 源:输入流。OutputStream Reader
* 目的:输出流.OutputStream Writer
* 2.操作的数据是否是纯文本。
* 是:字符流
* 不是:字节流。
* 3.当体系明确后,在明确要使用哪个具体的对象。
*  通过设备来进行区分:
*  源设备:内存,硬盘。键盘
*  目的设备:内存,硬盘,控制台。
*/

/*那么分别分析
* 源:InputStream Reader
* 是不是纯文本?是!Reader
*
* 设备:键盘。对应的对新啊格式System.in.
* 不是选择Reader吗?System.in对应的ushi字节流吗?
* 为了操作键盘的文本数据方便。转成字符流uanzhao字符串操作是最方便的。
* 所以既然明确Reader,那么就将System.in转换成Reader.
* 用了Reader体系中转换流,InputStreamReader
*
* InputStreamReader isr = new InputStreamReader(System.in);
* 需要提高效率吗?需要!BufferedReader
* BufferedReader bufr = new BufferedReader(isr);
*
* 目的:OutputStream Writer
* 是否是存文本。使用FileWriter.
* FileWriter fw = new FileWriter("c.txt");
* 需要提高效率吗?需要。
* BufferedWriter bufw = new BufferedWriter(fw);
*/

/**扩展一下,想要把录入的数据按照指定的编码表(utf-8),将数据存在文件中。
* 目的:OutputStream Writer
* 是否是存文本?是!Writer
* 设备:硬盘。一个问价。使用FileWriter.
* 但是FileWriter是使用的默认编码表。GBK
*
* 但是存储时,需要加入指定编码表utf-8.而知道那个的编码表只有转换流可以指定。
* 所以要使用的对象是OutputStreamWriter.
* 而该转换流对象要接收一个字节输出流。而且还可以操作的文件的字节输出流。FileOutputStream
* OutputStreamWriter osw = new OutputStreamWriter(new FileOutputstream("d.txt","uft-8"));
*
* 需要高效吗?需要
* BufferedWriter bufw = new BufferedWriter(ows);
* 所以,记住。转换流什么使用。字符和字节之间的桥梁,通常涉及字符编码转换时,需要用到转换流。
*
*
*练习:将一个文本数据打印在控制台上。要按照以上格式自己完成三个明确。
* @throws IOException
*/

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

// System.setIn(new FileInputStream("c:\\MyMenuDemo.java"));
System.setOut(new PrintStream("c:\\zzz.txt"));

//键盘最常见写法。
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out));

String line = null;
while((line=bufr.readLine())!=null){
if("over".equals(line))
break;
bufw.write(line.toUpperCase());
bufw.newLine();
bufw.flush();
}
bufr.close();
bufw.close();
}

}
/**
* IO
* @author xinglefly
* @version 1
*/
/*
* 字节流和字符流
* 字节流两个基类
* InputStream(读) OutputStream(写)
* 字符流两个基类
* Reader Writer
* 先学习一下字符流的特点
* 既然IO流是用于操作数据的,那么数据的最常见体现是:文件
* 那么先以操作文件为主来演示
* 要求:在硬盘上,创建一个文件并写入一些文字数据。
* 找到一个专门用于操作文件的Writer子类对象。FileWriter.后缀名是父类名,前缀名是该流对象的功能。
*/
public class FileWriterDemo {
/*public static void main(String[] args)throws IOException{
//创建一个FileWriter对象,该对象一被初始化就必须要明确被操作的文件。
//而且该文件会被创建到指定目录下。如果该目录下已有同名文件,将被覆盖。
//其实该步就是在明确数据要存放的目的地。
FileWriter fw = new FileWriter("c:\\demo.txt");

//调用writer方法,将字符串写入到流中。
fw.write("abcdd");

//刷新流对行啊中的缓冲中的数据
//将数据刷到目的地中
// fw.flush();
fw.write("hahah");

//关闭流资源,但是关闭之前会刷新一次内部的缓冲中的数据
//将数据刷到目的地中。
//和flush区别:flush刷新后,流可以继续使用,close舒心后,会将流关闭
fw.close();
}*/
public static void main(String[] args1){
FileWriter fw = null;
try{
fw = new FileWriter("c:\\demos.txt",true);
fw.write("abdejifejljiajfldjfieut\r\n jfjialfjdie");
fw.write("Tanks");
System.out.println(fw);
}catch(IOException e){
e.printStackTrace();
}finally{
if(fw!=null)
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}

缓冲区
import java.io.*;
/**
* BufferWriter
* 缓冲区的出现是为了提高流的操作效率出现的。
* 所以在创建缓冲区之前,必须要先有流对象。
* 该缓冲区中提供了一个跨平台的换行符。
* newline();
* @author xinglefly
* @version 1
*/
public class BufferWriterDemo {
public static void main(String[] args)throws IOException{
//创建一个字符写入流对象。
FileWriter fw = new FileWriter("c:\\ppt.txt");
//为了提高字符写入流效率。假如缓冲技术。
//只要将需要被提高效率的流对象作为参数传递给缓冲区的构造函数即可。
BufferedWriter bufw = new BufferedWriter(fw);
for(int i=0;i<5;i++){
bufw.write("abcddfefe");
bufw.newLine();
}
//记住,只要用到缓冲区,酒啊要记得刷新。
// bufw.flush();
bufw.close();
}
}

/**
* BufferedReader类中特有方法readline的原理后,可以自定义一个类中包含一个功能和readline一致的方法
* 来模拟一下BufferedReader
* @author xinglefly
* @version 1
*/

public class MyBufferedReader {
private FileReader r;
MyBufferedReader(FileReader r){
this.r=r;
}
//可以一次读一行数据的方法。
public String myReadLine()throws IOException{
//定义一个临时容器,原BufferReader封装的是字符数组。
//为了演示方便。定义一个StringBuilder容器。因为最终还是要将数据变成字符串。
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() throws IOException{
r.close();
}

public static void main(String[] args)throws IOException{
FileReader fr = new FileReader("c:\\MyMenuDemo.java");
MyBufferedReader b =  new MyBufferedReader(fr);
String line = null;
while((line=b.myReadLine())!=null){
System.out.println(line);
}
b.myClose();
}
}

文件流
/**
* File常见方法:
* 1.创建
* boolean createNewFile():在制定位置创建文件,如果该文件已经存在,则不创建,返回false.
* 和输出流不一样,输出流对象一建立创建文件。而且文件已经存在,会覆盖。
* boolean mkdir():创建文件夹
* boolean mkdirs():创建多级文件夹
* 2.删除
* boolean delete():
* void deleteOnExit();在程序退出时删除制定文件
*
* 3.判断
* boolean exists():文件是否存在
* isFile():
* isDirectory();
* isHidden();
* isAbsolute();
* 4.获取信息
* @author xinglefly
* @version 1
*/

public class FileDemo {
public static void main(String[] args) throws IOException{
// consMethod();
// listDemo();
listRootsDemo();


File dir = new File("e:\\");
File[] arr = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
/*sop("dir:"+dir+".....name::"+name);
if(name.endsWith(".java"))
return true;
else
return false;*/
return name.endsWith(".java");
}
});
sop("len:"+arr.length);
for(File f:arr){
sop(f);
}
}


//创建File对象
public static void consMethod() throws IOException{
File f1 = new File("c:\\a.txt");
File f2 = new File("c:\\abc","b.txt");

File d = new File("c:\\abc");
File f3 = new File(d,"c:\\c.txt");
sop("f1:"+f1);
sop("f2:"+f2);
sop("f3:"+f3);
File f4 = new File("c:\\"+File.separator+"abc"+File.separator+"zzz"+File.separator+"a.txt");
sop("f4:"+f4);

File f = new File("c:\\java\\day\\file2.txt");
// f.createNewFile();
// f.mkdir();

//记住在判断文件对象是否是文件或者目的时,必须要先判断该文件对象封装的内容是否存在。
//通过exists判断。
sop("dir:"+f.isDirectory());
sop("file:"+f.exists());
}
//获取文件列表
public static void listDemo(){
File f = new File("c:\\");
String [] names = f.list();//调用list方法的file对象必须是封装一个目录。该目录还必须存在。
for(String name:names){
sop(name);
}
}
public static void listRootsDemo(){
File[] files = File.listRoots();
for(File f:files){
sop(f);
}
}
public static void getEndsWith(){

}
public static void sop(Object obj){
System.out.println(obj);
}

}
import java.io.File;

/**
* 列出指定目录下文件或者文件夹,包含子目录中的内容。
* 也就是列出指定目录下所有内容。
*
* 因为目录中还有目录,只要使用同一个列出目录功能的函数完成即可。
* 在列出过程中出现的还是目录的话,还可以再次调用本功能。
* 也就是函数自身调用自身。
* 这种表现形式,或者编程手法,成为递归。
*
* 递归要注意:
* 1.限定条件。
* 2.要注意递归的次数。尽量避免内存溢出。
* @author xinglefly
* @version 1
*/
public class FileDemo3 {
public static void main(String[] args){
File dir = new File("C:\\tt");
showDir(dir,2);
// toBin(6);
// int n= getSum(10000);
// System.out.println("n="+n);
removeDir(dir);
}
public static int getSum(int n){
if(n==1)
return 1;
return n+getSum(n-1);
}
public static void toBin(int num){
if(num>0){
toBin(num/2);
sop(num%2);
}
}
public static String getLever(int level){
StringBuilder sb = new StringBuilder();
sb.append("|--");
for(int x=0;x<level;x++){
// sb.append("|--");
sb.insert(0, "|");
}
return sb.toString();
}
public static void showDir(File dir,int level){
System.out.println(dir);
level++;
File[] files = dir.listFiles();
for(int x=0;x<files.length;x++){
if(files[x].isDirectory())
showDir(files[x],level);
else
System.out.println(getLever(level)+files[x]);
}
}
//删除原理
//在window中,删除目录从里面往外删除的
//既然是从里往外删除。就需要用到递归。
public static void removeDir(File dir){
File[] files = dir.listFiles();
for(int x=0;x<files.length;x++){
if(files[x].isDirectory())
removeDir(files[x]);
else
System.out.println(files[x].toString());
}
System.out.println(dir+"::dir::"+dir.delete());
}
public static void sop(Object obj){
System.out.println(obj);
}

}

内存流
import java.io.*;

/**
* ByteArrayStream
* 用于操作字节数组的流对象。
* ByteArrayInputStream:在构造的时候,需要接收数据源, 而且数据源是一个字节数组。
* ByteArrayOutputStream:在构造的时候,不用定义数据目的,因为该对象中内部封装了可变长度的字节数组。
* 这就是数据目的地。
*
* 因为这两个流对象都操作的数组,并没有使用系统资源。
* 所以,不用进行close关闭。
*
* 在流操作规律讲解时:
* 源设备:
* 键盘 System.in,硬盘 FileStream,内存ArrayStream。
* 目的设备:
* 控制台 System.out, 硬盘 FileStream, 内存ArrayStream.
* @author xinglefly
* @version 1
*/
public class ByteArrayDemo {
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());
}
}


打印流
import java.io.*;

/**
* 打印流:
* 该流提供了打印方法,可以将各种数据类型的数据都原样打印。
*
* 字节打印流:
* PrintStream
* 构造函数可以接收的参数类型。
* 1.File对象
* 2.字符串路径。String
* 3.字节输出流.OutputSteam
*
* 字符打印流:
* PrintWriter
* 构造函数可以接收的参数类型:
* 1.File对象。
* 2.字符串路径。String
* 3.字节输出流。OutputStream
* 4.字符输出流,Writer
* @author xinglefly
* @version 1
*/
public class PrintSteamDemo {
public static void main(String[] args) throws IOException{
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new FileWriter("c:\\a.txt"),true);
String line = null;
while((line=bufr.readLine())!=null){
if("over".equals(line))
break;
out.println(line.toUpperCase());
}
out.close();
bufr.close();

}
}

import java.io.*;
/**
* 通过刚才的键盘录入一行数据并打印其大写,发现其实就是读一行数据的原理。readline的方法
* 能不能直接使用readLine方法来完成键盘录入的一行数据的读取呢?
* readLine方法是字符流BufferedReader类中的方法
* 那么能不能将字节流转成字符流在使用字符流缓冲区得readLine方法呢?
* @author xinglefly
* @version 1
*/
public class TransStreamDemo {
public static void main(String[] args)throws IOException{
/*//获取键盘录入对象
InputStream in = System.in;
//将字节流对象转成字符流对象,使用转换流,InputStreamReader
InputStreamReader isr = new InputStreamReader(in);
//为了提高效率,将字符串进行缓冲区技术高效操作。BufferedReader
BufferedReader bufr = new BufferedReader(isr);*/

BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
/*OutputStream out = System.out;
OutputStreamWriter osw = new OutputStreamWriter(out);
BufferedWriter bufw = new BufferedWriter(osw);
*/
BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out));
String line = null;
while((line=bufr.readLine())!=null){
if("over".equals(line))
break;
// System.out.println(line.toUpperCase());
bufw.write(line.toUpperCase());
bufw.newLine();
bufw.flush();
}
bufr.close();
}

}


合并
/**
*
* @author xinglefly
* @version 1
*/
public class SequenceDemo {
public static void main(String [] args) throws IOException{
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();

}
}

import java.io.*;
import java.util.*;

public class SplitFile {
public static void main(String[] args) throws IOException{
// splitFile();
merge();
}
public static void merge() throws IOException{
ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
for(int x=1;x<=21279;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:\\0.jpg");
byte [] buf = new byte[1024*1024];
int len=0;
while((len=sis.read())!=-1){
fos.write(buf,0,len);
}
fos.close();
sis.close();
}
public static void splitFile() throws IOException{
FileInputStream fis = new FileInputStream("c:\\001.jpg");
FileOutputStream fos = null;

byte[] buf = new byte[1024*1024];

int len=0;
int count=1;
while((len=fis.read())!=-1){
fos=new FileOutputStream("c:\\splitfiles"+(count++)+".part");
fos.write(buf,0,len);
fos.close();
}
fis.close();

}

}
/**
*
* @author xinglefly
* @version 1
*/
public class PropertiesDemo {
public static void main(String[] args) throws IOException{
// setAndGet();
// method_1();
loadDemo();
}

public static void loadDemo() throws IOException{
Properties p = new Properties();
FileInputStream fis = new FileInputStream("c:\\systinfo.txt");

//将流中的数据加载进集合。
p.load(fis);
p.setProperty("wangwu", "39");
FileOutputStream fos = new FileOutputStream("c:\\info.txt");
p.store(fos, "haha");
p.list(System.out);

fos.close();
fis.close();


}

//演示,如何将流中的数据存储到集合中。
//想要将info.txt中键值数据存到集合中进行操作。
/*
* 1.用一个流和info.txt文件关联
* 2.读取一行数据,将该行数据用"="进行切割
* 3.等号左边作为键,右边作为值。存入到properties集合中即可。
*/
public static void method_1()throws IOException{
BufferedReader bufr = new BufferedReader(new FileReader("c:\\sysinfo.txt"));
String line = null;
Properties pro = new Properties();
while((line=bufr.readLine())!=null){
String [] arr = line.split("=");
System.out.println(arr[0]+"..."+arr[1]);
pro.setProperty(arr[0], arr[1]);
}
bufr.close();
System.out.println(pro);
}


public static void setAndGet(){
Properties p = new Properties();
p.setProperty("zhangsan", "30");
p.setProperty("lisi", "39");

System.out.println(p);
String value = p.getProperty("lisi");
System.out.println(value);
Set<String> names = p.stringPropertyNames();
for(String s:names){
System.out.println(s+"::"+p.getProperty(s));
}
}
}

/**
*
* @author xinglefly
* @version 1
*/

public class RunCount {
public static void main(String[] args) throws IOException{
/*
* 程序即使结束,该计数器的值也存在。
* 下次程序启动在会先加载该计数器的值并加1后在重新存储起来。
* 所以要建立一个配置文件。用于记录该软件的使用次数。
* 该配置文件使用键值对的形式。
* 这样便于阅读数据,并操作数据。
*
* 键值对数据是map集合。
* 数据是以文件形式存储,使用io技术。
* 那么map+io---->properties
*
* 配置文件可以实现应用程序数据的共享。
*/
Properties p = new Properties();
File file = new File("c:\\count.ini");
if(!file.exists())
file.createNewFile();
FileInputStream fis = new FileInputStream(file);
p.load(fis);
int count=0;
String value = p.getProperty("time");
if(value!=null){
count=Integer.parseInt(value);
if(count>=5){
System.out.println("您好,使用次数已到,拿钱!");
return ;
}
count++;
}

p.setProperty("time", count+"");
FileOutputStream fos = new FileOutputStream(file);
p.store(fos, "");
fos.close();
fis.close();
}
}

对像流
import java.io.*;

/**
* serializable 长期存储
* 堆类中封装的一些数据
* @author xinglefly
* @version 1
*/
class Person implements Serializable{
public static final long seriaVersonUID = 44L;
private String name;
transient int age;//关键字在堆中存在,不在文本中显示
static String country="cn";//静态是不能序列化的
Person(String name,int age,String country){
this.name=name;
this.age=age;
this.country=country;
}
public String toString(){
return "name:"+name+":"+age+":"+country;
}

}
public class ObjectStreamDemo {
public static void main(String[] args)throws Exception{
// Person p = new Person("zhangsan",32);
// writeObj();
readObj();
}
public static void writeObj(){
ObjectOutputStream out = null;
try{
out = new ObjectOutputStream(new FileOutputStream("c:\\obj.txt"));
out.writeObject(new Person("zhangsan",22,"EN"));
}catch(IOException e){
throw new RuntimeException("写入数据失败");
}finally{
try{
if(out!=null)
out.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
}
public static void readObj() throws Exception{
ObjectInputStream in = null;
try{
in = new ObjectInputStream(new FileInputStream("c:\\obj.txt"));
Person p = (Person)in.readObject();
System.out.println(p);
}catch(IOException e){
throw new RuntimeException("读取数据失败!");
}finally{
try{
if(in!=null)
in.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
}
}

管道流
/**
* 管道流
*
* @author xinglefly
* @version 1
*/
class Read implements Runnable{
public PipedInputStream pi;
Read(PipedInputStream pi){
this.pi=pi;
}
public void run(){
try{
byte[] buf = new byte[1024];

System.out.println("读取前,没有数据阻塞");
int len = pi.read(buf);
System.out.println("读到数据,阻塞结束");
String s = new String(buf,0,len);
System.out.println(s);
pi.close();
}catch(IOException e){
throw new RuntimeException("管道读取流失败");
}
}
}
class Write implements Runnable{
private PipedOutputStream out;
Write(PipedOutputStream out){
this.out=out;
}
public void run(){
try{
System.out.println("开始写入数据,请等待6秒");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.write("piped is ok".getBytes());
out.close();
}catch(IOException e){
throw new RuntimeException("写入失败");
}
}
}
public class PipedStreamDemo {
public static void main(String[] args) throws IOException{
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
in.connect(out);
Write w = new Write(out);
Read r = new Read(in);
new Thread(r).start();
new Thread(w).start();
}
}

随机Random
import java.io.*;
/**
* RandomAccessFile
* 这类不算是IO体系中子类,而是继承自Object。
* 内部封装了一个数组,而且通过指针对数组的元素进行操作。
* 可以通过getFilePointer获取指针对数组的元素进行操作。
* 同事可以通过seek改变指针的位置。
*
* 其实完成读写的原理就是内部封装了字节输入流和输出流。
* 通过构造函数可以看出,该类只能操作文件
* 而且操作文件还有模式:只读 r ,读写 rw等
*
* 如果模式为只读 r,不会常见文件。会去读取一个已存在文件,如果该文件不存在,则会出现异常。
* 如果模式rw,操作的文件不存在,会自动创建,如果存在不会覆盖。
* @author xinglefly
* @version 1
*/
public class RandomAceessFileDemo {
public static void main(String[] args) throws IOException{
// wirteFile();
readFile();
System.out.println(Integer.toBinaryString(258));

}
public static void readFile() throws IOException{
RandomAccessFile raf = new RandomAccessFile("c:\\ran.txt","r");
//调整对对象中指针
// raf.seek(8*0);
//跳过指定的字节数
raf.skipBytes(4);
byte[] by = new byte[1024];
raf.read();
String name=new String(by);
int age = raf.readInt();
System.out.println("name:"+name);
System.out.println("age:"+age);
raf.close();
}
public static void wirteFile() throws IOException{
RandomAccessFile raf = new RandomAccessFile("c:\\ran.txt","rw");
raf.write("李四".getBytes());
// raf.write(258);
raf.writeInt(258);
raf.write("zhangsan".getBytes());
raf.writeInt(22);
raf.close();
}
}

Runtime对象
/**
* Runtime对象
* 该类并没有提供构造函数。
* 说明不可以new对象。那么会直接想到该类中的方法都是静态的。
* 发现该类中还有非静态方法。
* 说明该类肯定会提供了方法获取本类对象。而且该方法是静态的,并返回值类型是本类类型。
* 由这个特点可以看出该类使用了单列设计模式完成。
*
* 该方式是static Runtime getRuntime();
* @author xinglefly
* @version 1
*/
public class RuntimeDemo {
public static void main(String[] args)throws Exception{
Runtime r = Runtime.getRuntime();
Process p = r.exec("notepad.exe  SystemDemo.java");
Thread.sleep(4000);
p.destroy();
}
}


Exception
/**
* 错误日志的记录
* @author xinglefly
* @version 1
*/
public class ExceptionInfo {
public static void main(String[] args){
try{
int[] arr = new int[2];
System.out.println(arr[3]);
}catch(Exception e){
try{
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = sdf.format(d);
PrintStream ps = new PrintStream("c:\\excetpion.log");
ps.println(s);
System.setOut(ps);
}catch(IOException ex){
throw new RuntimeException("日志文件创建失败");
}
e.printStackTrace(System.out);
}

}
}


编码
/**
*
* @author xinglefly
* @version 1
*/
public class EncodeDemo {
public static void main(String [] args) throws Exception{
String s = "你好";
byte[] b = s.getBytes("GBK");
System.out.println(Arrays.toString(b));
String s1 = new String(b,"utf-8");
System.out.println("s1="+s1);

//对s1进行iso8859-1编码。
byte[] b2 = s1.getBytes("iso8859-1");
System.out.println(Arrays.toString(b2));
String s2 = new String(b,"GBK");
System.out.println("s2="+s2);

System.out.println("--------------------------");
String a = "联通";
byte[] by = a.getBytes("gbk");
for(byte bt:by){
System.out.println(Integer.toBinaryString(bt&255));
}
}
}