1.将字节流用字符流的形式输出
public class StreamtoChar {
public static void main(String[] args) throws Exception {
File file=new File("d:"+File.separator+"mytest.txt");
Writer outer=new OutputStreamWriter(new FileOutputStream(file));
outer.write("hello world!!");
outer.close();
}
}
2.将字节流用字符流的形式读入
public class StreamtoChar {
public static void main(String[] args) throws Exception {
File file=new File("d:"+File.separator+"mytest.txt");
//字节流变字符流
Reader reader=new InputStreamReader(new FileInputStream(file));
char mychar[]=new char[1024];
int len=reader.read(mychar);
System.out.println(new String(mychar,0,len));
reader.close();
}
}
3.使用转换流读写字符
输出时如果是文件,则使用Filexxx,如果是内存则使用ByteArrayxxx.
public class StreamtoChar {
public static void main(String[] args) throws Exception {
String string="HELLO WORLD";
ByteArrayInputStream bis=null;
ByteArrayOutputStream bos=null;
//向内存中输出内容(实际就是读入)
bis=new ByteArrayInputStream(string.getBytes());
//准备从内存中流中读取内容(实际上是输出)
bos=new ByteArrayOutputStream();
int temp=0;
while ((temp=bis.read())!=-1) {
char mychar=(char)temp;//读取的数字转化为char字符
bos.write(Character.toLowerCase(mychar));
}
//所有的数据就全部在ByteArrayOutputStream中
String newStr=bos.toString();//取出内容
System.out.println(newStr);
bis.close();
bos.close();
}
}
4.管道流连接两个线程
使用connect()方法连接两个管道流
class Send implements Runnable{
private PipedOutputStream pos=null;//管道输出流
public Send() {
this.pos=new PipedOutputStream();
}
@Override
public void run() {
String string="Hello World";
try {
this.pos.write(string.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
pos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//得到此线程的管道输出流
public PipedOutputStream getPos() {
return this.pos;
}
}
class Receive implements Runnable{
private PipedInputStream pis=null;//管道输入流
public Receive() {
this.pis=new PipedInputStream();
}
@Override
public void run() {
byte mybyte[]=new byte[1024];
int len=0;
try {
len=this.pis.read(mybyte);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(new String(mybyte,0,len));
try {
pis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public PipedInputStream getPis() {
return this.pis;
}
}
public class StreamtoChar {
public static void main(String[] args) {
Send send=new Send();
Receive receive=new Receive();
//连接管道
try {
send.getPos().connect(receive.getPis());
} catch (IOException e) {
e.printStackTrace();
}
new Thread (send).start();
new Thread(receive).start();
}
}
5.打印流
public class StreamtoChar {
public static void main(String[] args) {
PrintStream ps=null;
try {
//需要接受一个File对象作为参数
ps=new PrintStream(new File("d:"+File.separator+"mytest.txt"));
ps.print("hello");
ps.println("World");
ps.println("1+2="+1+2);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
5.打印流(使用包装流)
这是一种装饰设计,实际上还是outPutStream
public class StreamtoChar {
public static void main(String[] args) {
PrintStream ps=null;
try {
//需要接受一个File对象作为参数
ps=new PrintStream(new FileOutputStream(new File("d:"+File.separator+"mytest.txt")));
ps.print("hello");
ps.println("World!!");
ps.println("1+2="+1+2);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
6.打印流(格式化输出,c语言风格)
public class StreamtoChar {
public static void main(String[] args) {
PrintStream ps=null;
try {
//需要接受一个File对象作为参数
ps=new PrintStream(new FileOutputStream(new File("d:"+File.separator+"mytest.txt")));
ps.print("hello");
String name="ncepu";
int age=23;
float score=990.34f;
char sex='M';
//c语言风格的输出
ps.printf("姓名:%s 年龄:%d 成绩:%f 性别: %c",name,age,score,sex);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ps.close();
}
}
7.缓冲流接受键盘输入
public class StreamtoChar {
public static void main(String[] args) {
BufferedReader bufferedReader=null;
bufferedReader=new BufferedReader(new InputStreamReader(System.in));
String string=null;
System.out.println("请输入内容");
try {
string=bufferedReader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("输入的内容为"+string);
}
}
7.IO实例-加法操作
class InputData{
private BufferedReader br=null;
public InputData() {
this.br=new BufferedReader(new InputStreamReader(System.in));
}
public String getString(String info) {
String tempString=null;
System.out.println(info);
try {
tempString=br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tempString;
}
public int getInt(String info,String err) {
int temp=0;
boolean flag=true;
while (flag) {
String string=this.getString(info);
if (string.matches("^\\d+$")) {//使用正则表达式判断文本是否有数字组成
temp=Integer.parseInt(string);
flag=false;
}else {
System.out.println(err);
}
}
return temp;
}
}
public class StreamtoChar {
public static void main(String[] args) {
int i=0;
int j=0;
InputData inputData=new InputData();
i=inputData.getInt("请输入第一个数字", "输入的必须是数字,请重新输入");
j=inputData.getInt("请输入第二个数字", "输入的必须是数字,请重新输入");
System.out.println(i+j);
}
}
7.数据流(格式化输出)
public class StreamtoChar {
public static void main(String[] args) throws Exception {
//声明数据输出流对象
DataOutputStream dataOutputStream=null;
File file=new File("D:"+File.separator+"mytest.txt");
dataOutputStream =new DataOutputStream(new FileOutputStream(file));
//准备数据格式
String names[]= {"衬衣","手套","围巾"};
float prices[]= {98.3f,30.3f,50.5f};
int nums[]= {3,2,1};
for (int i = 0; i < nums.length; i++) {
dataOutputStream.writeChars(names[i]);//写入字符串
dataOutputStream.writeChar('\t');
dataOutputStream.writeFloat(prices[i]);
dataOutputStream.writeChar('\t');
dataOutputStream.writeInt(nums[i]);
dataOutputStream.writeChar('\n');
}
dataOutputStream.close();
}
}
8.数据流(格式化读取)
public class StreamtoChar {
public static void main(String[] args) throws Exception {
//声明数据输入流对象
DataInputStream dataInputStream=null;
File file=new File("D:"+File.separator+"mytest.txt");
dataInputStream =new DataInputStream(new FileInputStream(file));
//准备数据格式
String names=null;
float prices=0.0f;
int nums=0;
char temp[]=null;//接受商品名称
int len=0;//保存读取数据的个数
char mychar=0;
try {
while (true) {
temp=new char[200];//开闭空间
while ((mychar=dataInputStream.readChar())!='\t') {
temp[len]=mychar;
len++;
}
names=new String(temp,0,len);//讲字符数组变成字符
prices=dataInputStream.readFloat();//读取价格
dataInputStream.readChar();//读取\t
nums=dataInputStream.readInt();//读取int
dataInputStream.readChar();//读取\n
System.out.printf("名称:%s 价格:%5.2f 数量:%d\n",names,prices,nums);
}
} catch (Exception e) {
// TODO: handle exception
}
dataInputStream.close();
}
}
9.合并流(合并两个流)
public class StreamtoChar {
public static void main(String[] args) throws Exception {
InputStream inputStream1=null;
InputStream inputStream2=null;
OutputStream outputStream=null;
SequenceInputStream sequenceInputStream=null;
inputStream1=new FileInputStream("D:"+File.separator+"a.txt");
inputStream2=new FileInputStream("D:"+File.separator+"b.txt");
outputStream=new FileOutputStream("D:"+File.separator+"ab.txt");
sequenceInputStream=new SequenceInputStream(inputStream1,inputStream2);
int temp=0;
while ((temp=sequenceInputStream.read())!=-1) {
outputStream.write(temp);
}
sequenceInputStream.close();
inputStream1.close();
inputStream2.close();
outputStream.close();
}
}
10.压缩流(压缩包制作)
需要导java.util.zip包,使用ZipOutPutStream流
public class StreamtoChar {
public static void main(String[] args) throws Exception {
//定义原始文件对象
File file=new File("D:"+File.separator+"mytest.txt");
//声明压缩文件对象
File filezip=new File("D:"+File.separator+"mytest.zip");
InputStream inputStream=new FileInputStream(file);
ZipOutputStream zipOutputStream=null;
zipOutputStream=new ZipOutputStream(new FileOutputStream(filezip));
//设置zipEntry名字
zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
zipOutputStream.setComment("fengraytech");//设置注释
int temp=0;
while((temp=inputStream.read())!=-1) {
zipOutputStream.write(temp);
}
inputStream.close();
zipOutputStream.close();
}
}
11.压缩流(文件夹压缩包制作)
ZipFile类
public class StreamtoChar {
public static void main(String[] args) throws Exception {
//定义原始文件对象
File file=new File("D:"+File.separator+"mytest");
//声明压缩文件对象
File filezip=new File("D:"+File.separator+"mytestdir.zip");
InputStream inputStream=null;
ZipOutputStream zipOutputStream=null;
zipOutputStream=new ZipOutputStream(new FileOutputStream(filezip));
//多少个文件设置多少个zipEntry对象
if(file.isDirectory()) {
File list[] =file.listFiles();//列出全部文件
for (int i = 0; i < list.length; i++) {
inputStream=new FileInputStream(list[i]);
zipOutputStream.putNextEntry(new ZipEntry(file.getName()+
File.separator+list[i].getName()));
int temp=0;
while((temp=inputStream.read())!=-1) {
zipOutputStream.write(temp);
}
inputStream.close();
}
}
zipOutputStream.close();
}
}
11.压缩流(解压缩文件)
public class StreamtoChar {
public static void main(String[] args) throws Exception {
//定义原始文件对象
File file=new File("D:"+File.separator+"mytest.zip");//找到压缩文件
File outputFile=new File("d:"+File.separator+"mytest_unzip.txt");//设置解压缩文件和路径
ZipFile zipFile=new ZipFile(file);//实例化zipFile对象
System.out.println("压缩文件的名称"+zipFile.getName());
ZipEntry entery=zipFile.getEntry("mytest.txt");//得到一个压缩实体
OutputStream outputStream=new FileOutputStream(outputFile);//实例化输出流
InputStream inputStream=zipFile.getInputStream(entery);
int temp=0;
while ((temp=inputStream.read())!=-1) {
outputStream.write(temp);
}
inputStream.close();
outputStream.close();
}
}
12.压缩流(解压缩文件夹)
public class StreamtoChar {
public static void main(String[] args) throws Exception {
//定义原始文件对象
File file=new File("D:"+File.separator+"mytestdir.zip");//找到压缩文件
File outFile=null;
ZipFile zipFile=new ZipFile(file);
ZipEntry entry=null;
//定义压缩输入流
ZipInputStream zipInputStream=null;
OutputStream outputStream=null;
InputStream input=null;
zipInputStream=new ZipInputStream(new FileInputStream(file));
while((entry=zipInputStream.getNextEntry())!=null) {
System.out.println("解压缩:"+entry.getName()+"文件");
outFile=new File("D:"+File.separator+entry.getName());
if (!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdir();
}
if (outFile.exists()) {
outFile.createNewFile();
}
input=zipFile.getInputStream(entry);//得到每个实体的输入流
//实例化文件输出流
outputStream=new FileOutputStream(outFile);//指定输出文件夹
int temp=0;
while ((temp=zipInputStream.read())!=-1) {
outputStream.write(temp);
}
input.close();
outputStream.close();
}
zipInputStream.close();
}
}
13.对象序列化(自动序列化)
class Person implements Serializable {
private static final long serialVersionUID=1L;
private String name;
private int age;
public Person(String name,int age) {
this.name=name;
this.age=age;
}
public String toString() {
return "姓名:"+this.name+" 年龄:"+this.age;
}
}
public class SerialDemo{
public static void main(String[] args) throws FileNotFoundException, IOException {
File file=new File("D:"+File.separator+"mytest.txt");
//声明对象输出流
ObjectOutputStream objectOutputStream=null;
OutputStream outputStream=new FileOutputStream(file);
objectOutputStream=new ObjectOutputStream(new FileOutputStream(file));
objectOutputStream.writeObject(new Person("张三",20));
objectOutputStream.close();
}
}
14.反序列化
public class SerialDemo{
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
File file=new File("D:"+File.separator+"mytest.txt");
//声明对象输出流
ObjectInputStream objectInputStream=null;
InputStream inputStream=new FileInputStream(file);
objectInputStream=new ObjectInputStream(inputStream);
Object object=objectInputStream.readObject();
objectInputStream.close();
System.out.println(object);
}
}
15.手动序列化(Extenalizable接口)
class Person implements Externalizable {
private static final long serialVersionUID=1L;
private String name;
private int age;
//需要定义一个无参构造方法,否则反序列化的时候会报错
public Person() {}
public Person(String name,int age) {
this.name=name;
this.age=age;
}
public String toString() {
return "姓名:"+this.name+" 年龄:"+this.age;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(this.name);;
out.writeInt(this.age);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.name=(String) in.readObject();
this.age=in.readInt();
}
}
public class SerialDemo{
public static void main(String[] args) throws Exception {
deser();
}
public static void ser() throws Exception{
File file=new File("D:"+File.separator+"mytest.txt");
//声明对象输出流
ObjectOutputStream objectOutputStream=null;
OutputStream outputStream=new FileOutputStream(file);
objectOutputStream=new ObjectOutputStream(new FileOutputStream(file));
objectOutputStream.writeObject(new Person("张三",20));
objectOutputStream.close();
}
public static void deser() throws Exception{
File file=new File("D:"+File.separator+"mytest.txt");
//声明对象输入流
ObjectInputStream objectInputStream=null;
InputStream inputStream=new FileInputStream(file);
objectInputStream=new ObjectInputStream(inputStream);
Object object=objectInputStream.readObject();
objectInputStream.close();
System.out.println(object);
}
}
16.序列化一组对象(数组对象化)
class Person implements Externalizable {
private static final long serialVersionUID=1L;
private String name;
private int age;
//需要定义一个无参构造方法,否则反序列化的时候会报错
public Person() {}
public Person(String name,int age) {
this.name=name;
this.age=age;
}
public String toString() {
return "姓名:"+this.name+" 年龄:"+this.age;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(this.name);;
out.writeInt(this.age);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.name=(String) in.readObject();
this.age=in.readInt();
}
}
public class SerialDemo{
public static void main(String[] args) throws Exception {
Person persons[]= {new Person("张三",30),new Person("李四",24),new Person("王五",34)};
ser(persons);
Object object[]=(Object[])deser();
for (Object testObj : object) {
System.out.println(testObj);
}
}
public static void ser(Object obj) throws Exception{
File file=new File("D:"+File.separator+"mytest.txt");
//声明对象输出流
ObjectOutputStream objectOutputStream=null;
OutputStream outputStream=new FileOutputStream(file);
objectOutputStream=new ObjectOutputStream(new FileOutputStream(file));
objectOutputStream.writeObject(obj);
objectOutputStream.close();
}
public static Object[] deser() throws Exception{
File file=new File("D:"+File.separator+"mytest.txt");
//声明对象输入流
ObjectInputStream objectInputStream=null;
InputStream inputStream=new FileInputStream(file);
objectInputStream=new ObjectInputStream(inputStream);
Object object[]=(Object[])objectInputStream.readObject();
objectInputStream.close();
//System.out.println(object);
return object;
}
}
16.IO总结收尾:一个利用io做的简单的投票程序
class Student implements Comparable<Student>{
private int stuNo;
private String name;
private int vote;
public Student(int stuNo, String name, int vote) {
this.stuNo = stuNo;
this.name = name;
this.vote = vote;
}
public int getStuNo() {
return stuNo;
}
public void setStuNo(int stuNo) {
this.stuNo = stuNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getVote() {
return vote;
}
public void setVote(int vote) {
this.vote = vote;
}
@Override
public int compareTo(Student o) {
if (this.vote<o.vote) {
return 1;
}else if (this.vote>o.vote) {
return -1;
}
return 0;
}
}
class Operate{
private Student student[]= {new Student(1, "张三", 0),new Student(2, "李四", 0),new Student(3,"王五", 0),new Student(4, "赵六", 0)};
private boolean flag=true;
public Operate() {
this.printInfo();//先输出候选人信息
while (flag) {
this.vote();
}
this.printInfo();//输出候选人投票后的信息
this.getResult();
}
private void getResult() {
Arrays.sort(this.student);
System.out.println("投票最终结果:"+this.student[0].getName()+"同学最终以:"+this.student[0].getVote()+"票当选");
}
public void printInfo() {
for (int i = 0; i < student.length; i++) {
System.out.println(this.student[i].getStuNo()+":"
+this.student[i].getName()
+this.student[i].getVote());
}
}
public void vote() {
InputData input=new InputData();
int num=input.getInt("请输入班长候选人代号(数字):", "此选票无效,请输入正确的候选人代号");
switch (num) {
case 0:
this.flag=false;
break;
case 1:
this.student[0].setVote(this.student[0].getVote()+1);
break;
case 2:
this.student[1].setVote(this.student[1].getVote()+1);
break;
case 3:
this.student[2].setVote(this.student[2].getVote()+1);
break;
case 4:
this.student[3].setVote(this.student[3].getVote()+1);
break;
default:
System.out.println("此选票无效,请输入争取的候选人代号");
break;
}
}
}
class InputData{
private BufferedReader bufferedReader=null;
public InputData() {
this.bufferedReader=new BufferedReader(new InputStreamReader(System.in));
}
public String getString(String info) {
String temp=null;
System.out.println(info);
try {
temp=this.bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return temp;
}
public int getInt(String info,String string) {
int temp=0;
String str=null;
boolean flag=true;
while (flag) {
str=this.getString(info);
if (str.matches("\\d+")) {
temp=Integer.parseInt(str);
flag=false;
}else {
System.out.println(string);
}
}
return temp;
}
}
public class Vote {
public static void main(String[] args) {
new Operate();
}
}