---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------
1.IO流(概述)
字符流的两个基类:Reader Writer
字节流的两个基类:InputStream OutputStream
2.IO流(FileWriter)
需求:在硬盘上创建一个文件并写入一些文字数据。
代码:
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
//创建一个FileWriter对象。该对象一被初始化就必须要明确被操作的文件。
//而且该文件会被创建到指定目录下。如果该目录下已有同名文件,将被覆盖。
//其实该步就是在明确数据要存放的目的地。
Writer w=new FileWriter("d:/a.txt");
//调用write方法,将字符串写入到流中。
w.write("nihao");
//刷新流对象中的缓冲中的数据。
//将数据刷到目的地中。
w.flush();
//关闭流资源,但是关闭之前会刷新一次内部的缓冲中的数据。
//将数据刷到目的地中。
//和flush区别:flush刷新后,流可以继续使用,close刷新后,会将流关闭。
w.close();
}
}
3.IO流(IO异常处理方式)
IO异常处理示例代码:
import java.io.*;
class Test
{
public static void main(String[] args)
{
FileWriter fw=null;
try
{
fw=new FileWriter("d:/a.txt");
fw.write("aaa");
fw.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(fw!=null)
fw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
4.IO流(文件的续写)
FileWriter fw=new FileWriter(“Demo.txt”,true);
传递一个true参数,代表不覆盖已有的文件,并在已有的文件的末尾处进行数据的续写,如果没有该文件,则创建。
5.IO流(文本文件读取方式一)
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
//创建一个文件读取流对象,和指定名称的文件相关联。
//要保证该文件是已经存在的,如果不存在,会发生异常FileNotFoundException
FileReader fr=new FileReader("d:/a.txt");
//调用读取流对象的read方法。
//read():一次读一个字符。而且会自动往下读。
int ch=0;
while((ch=fr.read())!=-1)
{
System.out.print((char)ch);
}
fr.close();
}
}
6.IO流(文本文件读取方式二)
通过字符数组进行读取示例代码:
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
FileReader fr=new FileReader("d:/a.txt");
char[] buf=new char[1024];
int n=0;
while((n=fr.read(buf))!=-1)
{
String str=new String(buf,0,n);
System.out.println(str);
}
fr.close();
}
}
7.IO流(文本文件读取练习)
读取一个java文件到控制台上。示例代码:
import java.io.*;
class Test
{
public static void main(String[] args)
{
FileReader fr=null;
try
{
fr=new FileReader("D:/Test.java");
char[] buf=new char[1024];
int num=0;
while((num=fr.read(buf))!=-1)
{
String str=new String(buf,0,num);
System.out.print(str);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(fr!=null)
fr.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
8.IO流(拷贝文本文件)
将D盘一个文本文件复制到C盘:
步骤:
1,在D盘创建一个文件。用于存储C盘文件中的数据。
2,定义读取流和C盘文件关联。
3,通过不断的读写完成数据存储。
4,关闭资源。
方式1(一个一个字符的读)代码:
import java.io.*;
class Test
{
public static void main(String[] args)
{
FileReader fr=null;
FileWriter fw=null;
try
{
fr=new FileReader("d:/Test.java");
fw=new FileWriter("c:/Test.java");
int num=0;
while((num=fr.read())!=-1)
{
fw.write((char)num);
}
}
catch (IOException e)
{
throw new RuntimeException("读写失败");
}
finally
{
try
{
if(fr!=null)
fr.close();
if(fw!=null)
fw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
方式2(通过缓冲数组读)代码:
import java.io.*;
class Test
{
public static void main(String[] args)
{
FileReader fr=null;
FileWriter fw=null;
try
{
fr=new FileReader("d:/Test.java");
fw=new FileWriter("c:/Test.java");
char[] buf=new char[1024];
int num=0;
while((num=fr.read(buf))!=-1)
{
String str=new String(buf,0,num);
fw.write(str);
}
}
catch (IOException e)
{
throw new RuntimeException("读写失败");
}
finally
{
try
{
if(fr!=null)
fr.close();
if(fw!=null)
fw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
9.IO流(BufferedWriter)
缓冲区的出现是为了提高流的操作效率而出现的。
所以在创建缓冲区之前,必须要先有流对象。
该缓冲区中提供了一个跨平台的换行符newLine();
示例代码:
import java.io.*;
class BufferedWriterDemo
{
public static void main(String[] args) throws IOException
{
//创建一个字符写入流对象。
FileWriter fw = new FileWriter("buf.txt");
//为了提高字符写入流效率。加入了缓冲技术。
//只要将需要被提高效率的流对象作为参数传递给缓冲区的构造函数即可。
BufferedWriter bufw = new BufferedWriter(fw);
for(int x=1; x<5; x++)
{
bufw.write("abcd"+x);
bufw.newLine();
bufw.flush();
}
//只要用到缓冲区,就要记得刷新。
bufw.flush();
//其实关闭缓冲区,就是在关闭缓冲区中的流对象。
bufw.close();
}
}
10.IO流(BufferedReader)
字符读取流缓冲区:BufferedReader
该缓冲区提供了一个一次读一行的方法 readLine,方便于对文本数据的获取。
当返回null时,表示读到文件末尾。
readLine方法返回的时候只返回回车符之前的数据内容。并不返回回车符。
示例代码:
import java.io.*;
class BufferedReaderDemo
{
public static void main(String[] args) throws IOException
{
//创建一个读取流对象和文件相关联。
FileReader fr = new FileReader("buf.txt");
//为了提高效率。加入缓冲技术。将字符读取流对象作为参数传递给缓冲对象的构造函数。
BufferedReader bufr = new BufferedReader(fr);
String line = null;
while((line=bufr.readLine())!=null)
{
System.out.print(line);
}
bufr.close();
}
}
11.IO流(通过缓冲区复制文本文件)
自定义一个类中包含一个功能和readLine一致的方法。来模拟一下BufferedReader
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args)
{
BufferedReader br=null;
BufferedWriter bw=null;
try
{
br=new BufferedReader(new FileReader("D:/Test.java"));
bw=new BufferedWriter(new FileWriter("C:/Test1.java"));
String str=null;
while((str=br.readLine())!=null)
{
bw.write(str);
bw.newLine();
bw.flush();
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(br!=null)
br.close();
if(bw!=null)
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
12.IO流(MyBufferedReader)
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args)
{
MyBufferedReader mbr=null;
try
{
mbr=new MyBufferedReader(new FileReader("d:/Test.java"));
String str=null;
while((str=mbr.myReadLine())!=null)
{
System.out.println(str);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(mbr!=null)
mbr.myclose();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
class MyBufferedReader
{
private Reader r=null;
public MyBufferedReader(Reader r)
{
this.r=r;
}
public String myReadLine()throws IOException
{
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);
}
if(sb.length()!=0) return sb.toString();
return null;
}
public void myclose() throws IOException
{
r.close();
}
}
13.IO流(装饰设计模式)
装饰设计模式:当想要对已有对象进行功能增强时,可以定义类,将已有对象传入,基于已有的功能,并提供加强功能,那么自定义的该类称为装饰类。
装饰类通常会通过构造方法接收被装饰的对象。并基于被装饰的对象的功能提供更强的功能。
BufferedReader同理。
14.IO流(LineNumberReader)
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args)
{
LineNumberReader lnr=null;
try
{
lnr=new LineNumberReader(new FileReader("d:/Test.java"));
String str=null;
while((str=lnr.readLine())!=null)
{
System.out.println(lnr.getLineNumber()+str);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(lnr!=null)
lnr.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
15.IO流(MyLineNumberReader)
模拟一个带行号的缓冲区对象:
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args)
{
MyLineNumberReader mlr=null;
try
{
mlr=new MyLineNumberReader(new FileReader("d:/Test.java"));
String str=null;
mlr.setLineNumber(100);
while((str=mlr.myReadLine())!=null)
{
System.out.println(mlr.getLineNumber()+str);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(mlr!=null)
mlr.myclose();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
class MyLineNumberReader extends MyBufferedReader
{
private int lineNumber;
public MyLineNumberReader(Reader r)
{
super(r);
}
public String myReadLine()throws IOException
{
lineNumber++;
return super.myReadLine();
}
public int getLineNumber()
{
return this.lineNumber;
}
public void setLineNumber(int lineNumber)
{
this.lineNumber=lineNumber;
}
}
class MyBufferedReader
{
private Reader r=null;
public MyBufferedReader(Reader r)
{
this.r=r;
}
public String myReadLine()throws IOException
{
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);
}
if(sb.length()!=0) return sb.toString();
return null;
}
public void myclose() throws IOException
{
r.close();
}
}
16.IO流(字节流File读写操作)
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
//writeFile();
//readFile1();
//readFile2();
readFile3();
}
//往硬盘上写数据
public static void writeFile()throws IOException
{
FileOutputStream fos=new FileOutputStream("d:/a.txt");
fos.write("nihaonihao".getBytes());
fos.close();
}
//一个一个的读
public static void readFile1() throws IOException
{
FileInputStream fis=new FileInputStream("d:/a.txt");
int ch=0;
while((ch=fis.read())!=-1)
{
System.out.print((char)ch);
}
fis.close();
}
//使用字节数组读,建议使用这种方式
public static void readFile2() throws IOException
{
FileInputStream fis=new FileInputStream("d:/a.txt");
byte[] buf=new byte[1024];
int num=0;
while((num=fis.read(buf))!=-1)
{
String str=new String(buf,0,num);
System.out.println(str);
}
fis.close();
}
//定义一个刚刚好的缓冲区,不用循环,不建议使用
public static void readFile3()throws IOException
{
FileInputStream fis=new FileInputStream("d:/a.txt");
byte[] buf=new byte[fis.available()];
fis.read(buf);
System.out.println(new String(buf));
fis.close();
}
}
17.IO流(拷贝图片)
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
FileInputStream fis=null;
FileOutputStream fos=null;
try
{
fis=new FileInputStream("d:/Desert.jpg");
fos=new FileOutputStream("c:/Desert.jpg");
byte[] buf=new byte[1024];
int num=0;
while((num=fis.read(buf))!=-1)
{
fos.write(buf,0,num);
}
}
catch (IOException e)
{
throw new RuntimeException("读写图片失败");
}
finally
{
try
{
if(fis!=null)
fis.close();
if(fos!=null)
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
18.IO流(字节流的缓冲区)
利用字节流缓冲区BufferedInputStream,BufferedOutoutStream拷贝mp3
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try
{
bis=new BufferedInputStream(new FileInputStream("d:/1.mp3"));
bos=new BufferedOutputStream(new FileOutputStream("c:/2.mp3"));
int ch=0;
while((ch=bis.read())!=-1)
{
bos.write(ch);
}
}
catch (IOException e)
{
throw new RuntimeException("failed");
}
finally
{
try
{
if(bis!=null)
bis.close();
if(bos!=null)
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
19.IO流(自定义字节流缓冲区)
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
MyBufferedInputStream bis=null;
BufferedOutputStream bos=null;
try
{
bis=new MyBufferedInputStream(new FileInputStream("d:/1.mp3"));
bos=new BufferedOutputStream(new FileOutputStream("c:/2.mp3"));
int ch=0;
while((ch=bis.read())!=-1)
{
bos.write(ch);
}
}
catch (IOException e)
{
throw new RuntimeException("failed");
}
finally
{
try
{
if(bis!=null)
bis.close();
if(bos!=null)
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
class MyBufferedInputStream
{
private FileInputStream fis=null;
private int pos=0;
private int count=0;
private byte[] buf=new byte[1024];
MyBufferedInputStream(FileInputStream fis)
{
this.fis=fis;
}
public int read() throws IOException
{
if(count==0)
{
count = fis.read(buf);
if(count<0)
return -1;
pos = 0;
byte b = buf[pos];
count--;
pos++;
return b&255;
}
else if(count>0)
{
byte b = buf[pos];
count--;
pos++;
return b&0xff;
}
return -1;
}
public void close() throws IOException
{
fis.close();
}
}
20.IO流(读取键盘录入)
需求:通过键盘录入数据,当录入一行数据后,就对该行数据进行打印,如果录入的数据是over的活,就停止:
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
InputStream in=System.in;
StringBuilder sb=new StringBuilder();
int ch=0;
while((ch=in.read())!=-1)
{
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);
}
}
}
21.IO流(读取转换流)
键盘录入数据代码完善:
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=null;
while((str=br.readLine())!=null)
{
if(str.equals("over"))
break;
System.out.println(str.toUpperCase());
}
br.close();
}
}
22.IO流(写入转换流)
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
String str=null;
while((str=br.readLine())!=null)
{
if(str.equals("over"))
break;
bw.write(str.toUpperCase());
bw.newLine();
bw.flush();
}
br.close();
}
}
23.IO流(流操作的规律)
流操作的基本规律:
通过三个明确来完成。
1,明确源和目的。
源:输入流。InputStream Reader
目的:输出流。OutputStream Writer。
2,操作的数据是否是纯文本。
是:字符流。
不是:字节流。
3,当体系明确后,在明确要使用哪个具体的对象。
源设备:内存,硬盘。键盘
目的设备:内存,硬盘,控制台。
4.是否需要提高效率?
是:加缓冲区
不是:不加缓冲区
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:/aa.txt"),"utf-8"));
String str=null;
while((str=br.readLine())!=null)
{
if("over".equals(str))
break;
bw.write(str);
bw.newLine();
bw.flush();
}
br.close();
bw.close();
}
}
24.IO流(改变标准输入输出设备)
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
System.setIn(new FileInputStream("Test.java"));//改变标准输入设备
System.setOut(new PrintStream("zz.txt"));//改变标准输出设备
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
String str=null;
while((str=br.readLine())!=null)
{
if("over".equals(str))
break;
bw.write(str);
bw.newLine();
bw.flush();
}
br.close();
bw.close();
}
}
25.IO流(异常的日志信息)
示例代码:
import java.io.*;
import java.util.*;
import java.text.*;
import java.io.*;
class Test
{
public static void main(String[] args)
{
try
{
int[] arr=new int[3];
System.out.println(arr[3]);
}
catch (Exception e)
{
PrintStream ps=null;
try
{
Date d=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ps=new PrintStream("a.txt");
ps.println(sdf.format(d));
}
catch (Exception e1)
{
throw new RuntimeException("日志文件建立失败");
}
e.printStackTrace(ps);
}
}
}
26.IO流(File概述)
File类常见方法:
1,创建。
boolean createNewFile():在指定位置创建文件,如果该文件已经存在,则不创建,返回false。和输出流不一样,输出流对象一建立创建文件。而且文件已经存在,会覆盖。
boolean mkdir():创建文件夹。
boolean mkdirs():创建多级文件夹。
2,删除。
boolean delete():删除失败返回false。如果文件正在被使用,则删除不了返回falsel。
void deleteOnExit();在程序退出时删除指定文件。
3,判断。
boolean exists() :文件是否存在.
isFile():
isDirectory();
isHidden();
isAbsolute();
4,获取信息。
getName():
getPath():
getParent():
getAbsolutePath()
long lastModified()
long length()
renameTo()
27.IO流(File对象功能文件列表)
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args)
{
//listRootDemo();
//listDemo();
//FilterDemo();
ListFIlesDemo();
}
//列出系统有效盘符
public static void listRootDemo()
{
File[] files=File.listRoots();
for(File f:files)
{
System.out.println(f);
}
}
//列出某一个目录下所有的文件的名称
public static void listDemo()
{
File f=new File("c:/");
String[]names=f.list();
for(String name:names)
System.out.println(name);
}
//列出指定目录下所有的.java文件
public static void FilterDemo()
{
File dir=new File("d:/");
String[] arr=dir.list(new FilenameFilter(){
public boolean accept(File dir,String name)
{
return name.endsWith(".java");
}
});
for(String name:arr)
{
System.out.println(name);
}
}
//列出指定目录下所有文件的文件对象
public static void ListFIlesDemo()
{
File dir=new File("c:/");
File[] files=dir.listFiles();
for(File f:files)
System.out.println(f.getName());
}
}
28.IO流(列出目录下所有内容-递归)
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args)
{
showDir(new File("c:/"));
}
//列出指定目录下的所有目录,包括子目录
public static void showDir(File dir)
{
System.out.println(dir.getName())
File[] files=dir.listFiles();
for(int x=0;x<files.length;x++)
{
if(files[x].isDirectory())
showDir(files[x]);
else
System.out.println(files[x]);
}
}
}
29.IO流(列出目录下所有的内容-带层次)
示例代码;
import java.io.*;
class Test
{
public static void main(String[] args)
{
showDir(new File("c:/"),0);
}
//列出指定目录下的所有目录,包括子目录
public static void showDir(File dir,int level)
{
System.out.println(getLevel(level)+dir.getName());
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(getLevel(level)+files[x]);
}
}
public static String getLevel(int level)
{
StringBuilder sb=new StringBuilder();
sb.append("|--");
for(int x=0;x<level;x++)
sb.insert(0," ");
return sb.toString();
}
}
30.IO流(删除一个带内容的目录)
import java.io.*;
class Test
{
public static void main(String[] args)
{
deleteDir(new File("d:/test"));
}
//列出指定目录下的所有目录,包括子目录
public static void deleteDir(File dir)
{
File[] files=dir.listFiles();
for(int x=0;x<files.length;x++)
{
if(files[x].isDirectory())
deleteDir(files[x]);
else
System.out.println(files[x].delete());
}
System.out.println(dir.delete());
}
}
31.IO流(创建java文件列表)
示例代码:
import java.io.*;
import java.util.*;
class Test
{
public static void main(String[] args)
{
File dir=new File("d:/Test");
List<File> list=new ArrayList<File>();
fileToList(dir,list);
File file=new File(dir,"javaList.txt");
writeToFile(list,file);
}
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,File javaFile)
{
BufferedWriter bw=null;
try
{
bw=new BufferedWriter(new FileWriter(javaFile));
for(File f:list)
{
String path=f.getAbsolutePath();
bw.write(path);
bw.newLine();
bw.flush();
}
}
catch (IOException e)
{
throw new RuntimeException();
}
finally
{
try
{
if(bw!=null)
bw.close();
}
catch (Exception e)
{
throw new RuntimeException();
}
}
}
}
32.IO流(Properties简述)
Properties是Hashtable的子类,也就是说,它具备了Map集合的特点,而且它里面存储的键值对都是字符串,不需要泛型。是集合中和IO技术相结合的集合容器。
该对象的特点:可以用于键值对形式的配置文件。
示例代码:
import java.io.*;
import java.util.*;
class Test
{
public static void main(String[] args)
{
Properties prop=new Properties();
prop.setProperty("zhangsan",223+"");
prop.setProperty("lisi",33+"");
Set<String> names=prop.stringPropertyNames();
for(String name:names)
{
System.out.println(name+" "+prop.getProperty(name));
}
}
}
Properties存取配置文件:
示例代码:
import java.io.*;
import java.util.*;
class Test
{
public static void main(String[] args) throws IOException
{
FileInputStream fis=new FileInputStream("d:/info.txt");
Properties prop=new Properties();
//将配置文件加载到内存中
prop.load(fis);
prop.setProperty("zhangsan",89+"");
prop.list(System.out);
FileOutputStream fos=new FileOutputStream("d:/info.txt");
//将内存中的数据保存到硬盘上
prop.store(fos,"haha");
fis.close();
fos.close();
}
}
需求:用于记录应用程序的运行次数。
示例代码:
import java.io.*;
import java.util.*;
class Test
{
public static void main(String[] args) throws IOException
{
File f=new File("d:infom.properties");
if(!f.exists())
{
f.createNewFile();
}
FileInputStream fis=new FileInputStream(f);
Properties prop=new Properties();
prop.load(fis);
String value=prop.getProperty("time");
if(value==null)
{
prop.setProperty("time",1+"");
}
else
prop.setProperty("time",Integer.parseInt(value)+1+"");
FileOutputStream fos=new FileOutputStream(f);
prop.store(fos,"");
fis.close();
fos.close();
}
}
33.IO流(PrintWriter)
打印流:该流提供了打印方法,可以将各种数据类型的数据都原样打印。
PrintStream:字节打印流
构造函数可以接收的参数类型
1.File对象 File
2.字符串路径 String
3.字节输出流 OutputStream
PrintWriter:字符打印流
构造函数可以接收的参数类型
1.File对象 File
2.字符串路径 String
3.字节输出流 OutputStream
4.字符输出流 Writer
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(new FileWriter("d:/info.txt"),true);
String str=null;
while((str=br.readLine())!=null)
{
if("over".equals(str))
break;
pw.println(str.toUpperCase());
}
br.close();
pw.close();
}
}
34.IO流(合并流)
序列流:SequenceInputStream将多个流合并成一个读取流
示例代码:
import java.io.*;
import java.util.*;
class Test
{
public static void main(String[] args) throws IOException
{
Vector<FileInputStream> v=new Vector<FileInputStream>();
v.add(new FileInputStream("d:/1.txt"));
v.add(new FileInputStream("d:/2.txt"));
v.add(new FileInputStream("d:/3.txt"));
Enumeration<FileInputStream> en=v.elements();
SequenceInputStream sis=new SequenceInputStream(en);
FileOutputStream fos=new FileOutputStream("d:/4.txt");
byte[] buf=new byte[1024];
int ch=0;
while((ch=sis.read(buf))!=-1)
{
fos.write(buf,0,ch);
}
sis.close();
fos.close();
}
}
35.IO流(切割文件)
需求:切割文件,然后合并文件
示例代码:
import java.io.*;
import java.util.*;
class Test
{
public static void main(String[] args) throws IOException
{
split();
hebin();
}
//合并流
public static void hebin() throws IOException
{
ArrayList<FileInputStream> aL=new ArrayList<FileInputStream>();
for(int x=1;x<=15;x++)
{
aL.add(new FileInputStream("d:/"+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("d:/test.bmp");
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 split()throws IOException
{
FileInputStream fis=new FileInputStream("d:/1.bmp");
FileOutputStream fos=null;
byte[] buf=new byte[1024];
int len=0;
int count=1;
while((len=fis.read(buf))!=-1)
{
fos=new FileOutputStream("d:/"+count+".part");
count++;
fos.write(buf,0,len);
fos.close();
}
}
}
36.IO流(对象的序列化)
示例代码:
import java.io.*;
import java.util.*;
class Test
{
public static void main(String[] args) throws Exception
{
//writeObj();
readObj();
}
public static void writeObj()throws Exception
{
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("d:object.txt"));
oos.writeObject(new Person("lisi",34,"kr"));
oos.close();
}
public static void readObj()throws Exception
{
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("d:/object.txt"));
Person p=(Person)ois.readObject();
System.out.println(p);
ois.close();
}
}
class Person implements Serializable
{
public static final long serialVersionUID=42L;
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 this.name+" "+this.age+" "+this.country;
}
}
注意:
1如果这个类的成员就加了一个private的话,还想使用原来的序列化对象,在定义Person类的时候,自己定义一个UID。
public static final long serialVersionUID=42L;
2 静态不能被序列化,因为序列化的是堆内存,而静态的在方法区。
3如果对非静态成员也不想进行序列化的话,那么就加一个关键字修饰。
transient int age;
4一般不存成.txt文件,一般存为.object文件。
5.ObjectInputStream和ObjectOutputStream成对使用。
37.IO流(管道流)
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
PipedInputStream pis=new PipedInputStream();
PipedOutputStream pos=new PipedOutputStream();
pis.connect(pos);
new Thread(new Read(pis)).start();
new Thread(new Write(pos)).start();
}
}
class Read implements Runnable
{
private PipedInputStream in;
public Read(PipedInputStream in)
{
this.in=in;
}
public void run()
{
try
{
byte[] buf=new byte[1024];
int len=0;
while((len=in.read(buf))!=-01)
{
System.out.println(new String(buf,0,len));
}
}
catch (IOException e)
{
e.printStackTrace();
}finally
{
try
{
if(in!=null)
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
class Write implements Runnable
{
private PipedOutputStream out;
public Write(PipedOutputStream out)
{
this.out=out;
}
public void run()
{
try
{
try
{
Thread.sleep(6000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
out.write("pipe is coming".getBytes());
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(out!=null)
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
38.IO流(RandomAccessFile)
该类不算是IO体系的子类,而是直接继承自Object,但是IO包中的成员,因为它具备读和写功能,内部封装了一个byte数组,而且通过指针对数组中的元素进行操作,可以通过getFilePointer()获取指针位置,请过seek()改变指针位置。
其实完成读写对的原理:内部封装了字节数入流,字节输出流。
通过构造函数可以看出,该类只能操作文件,而且操作文件还有模式:只读r,读写rw。
如果模式为只读 r。不会创建文件。会去读取一个已存在文件,如果该文件不存在,则会出现异常。
如果模式rw。操作的文件不存在,会自动创建。如果存则不会覆盖。
示例代码:
写数据:
RandomAccessFile raf=new RandomAccessFile("d:/raf.txt","rw");
raf.write("张三".getBytes());
raf.writeInt(97);
raf.close();
读数据:
RandomAccessFile raf=new RandomAccessFile("d:/raf.txt","r");
byte[] buf=new byte[4];
int len=raf.read(buf);
int age=raf.readInt();
System.out.println(new String(buf,0,len)+" "+age);
调整对象的指针:raf.seek(8);/
跳过指定的字节数:raf.skipBytes(8);//它不能往回走
随机读写示例代码:
RandomAccessFile raf=new RandomAccessFile("d:/raf.txt","rw");
raf.seek(8*5);
raf.write("周期".getBytes());
raf.writeInt(89);
raf.close();
39.IO流(操作基本数据类型)
DataInputStream和DataOutputStream用于操作基本数据类型数据的流对象。
写数据示例代码:
DataOutputStream dos=new DataOutputStream(new FileOutputStream("d:/info.txt"));
dos.writeInt(123);
dos.writeBoolean(true);
dos.writeDouble(9.9);
dos.close();
读数据示例代码:
DataInputStream dis=new DataInputStream(new FileInputStream("d:/info.txt"));
System.out.println(dis.readInt());
System.out.println(dis.readBoolean());
System.out.println(dis.readDouble());
dis.close();
注:使用DataOutputStream中的writeUTF(),只能使用DataInputStream中的readUTF()读出来。
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
DataOutputStream dos=new DataOutputStream(new FileOutputStream("d:/info.txt"));
dos.writeUTF("你好");
dos.close();
DataInputStream dis=new DataInputStream(new FileInputStream("d:/info.txt"));
System.out.println(dis.readUTF());
dis.close();
}
}
40.IO流(转换流)
示例代码:
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
//写
OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("d:/gbk.txt"),"gbk");
osw.write("你好");
osw.close();
//读
InputStreamReader isr=new InputStreamReader(new FileInputStream("d:/gbk.txt"),"gbk");
char[]buf=new char[10];
int len=isr.read(buf);
System.out.println(new String(buf,0,len));
}
}
注意:如果写数据时用的编码表与读时候用的编码表不一致,则会出现乱码。
编码解码示例代码:
import java.util.*;
class Test
{
public static void main(String[] args)throws Exception
{
//编码
String s="你好";
byte[] b1=s.getBytes("GBK");
System.out.println(Arrays.toString(b1));
//解码
String s1=new String(b1,"GBK");
System.out.println(s1);
}
}
41.IO流(练习)
有五个学生,每个学生有3门课的成绩,
从键盘输入以上数据(包括姓名,三门课成绩),
输入的格式:如:zhagnsan,30,40,60计算出总成绩,
并把学生的信息和计算出的总分数高低顺序存放在磁盘文件"stud.txt"中。
1,描述学生对象。
2,定义一个可操作学生对象的工具类。
思想:
1,通过获取键盘录入一行数据,并将该行中的信息取出封装成学生对象。
2,因为学生有很多,那么就需要存储,使用到集合。因为要对学生的总分排序。
所以可以使用TreeSet。
3,将集合的信息写入到一个文件中。
示例代码:
import java.io.*;
import java.util.*;
class Test
{
public static void main(String[] args)throws Exception
{
Comparator<Student> cmp=Collections.reverseOrder();
Set<Student> stus=StudentInfoTool.getStudent(cmp);
StudentInfoTool.writeToFile(stus);
}
}
class Student implements Comparable<Student>
{
private String name;
private double english;
private double chinese;
private double math;
private double sum;
public Student(String name,double english,double chinese,double math)
{
this.name=name;
this.english=english;
this.chinese=chinese;
this.math=math;
this.sum=this.english+this.chinese+this.math;
}
public double getSum()
{
return this.sum;
}
public String getName()
{
return this.name;
}
public int hashCode()
{
return this.name.hashCode();
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("不是Student对象");
Student s=(Student)obj;
return this.getName().equals(s.getName())&&this.getSum()==s.getSum();
}
public int compareTo(Student s)
{
int num=new Double(this.getSum()).compareTo(s.getSum());
if(num==0)
return this.getName().compareTo(s.getName());
return num;
}
public String toString()
{
return this.name+" "+this.english+" "+this.chinese+" "+this.math+" "+this.sum;
}
}
class StudentInfoTool
{
public static Set<Student> getStudent(Comparator<Student> cmp)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=null;
Set<Student> stus=null;
if(cmp==null)
stus=new TreeSet<Student>();
else
stus=new TreeSet<Student>(cmp);
while((str=br.readLine())!=null)
{
if("over".equals(str))
break;
String []info=str.split(",");
Student stu=new Student(info[0],Double.parseDouble(info[1]),Double.parseDouble(info[2]),Double.parseDouble(info[3]));
stus.add(stu);
}
br.close();
return stus;
}
public static Set<Student> getStudent()throws IOException
{
return getStudent(null);
}
public static void writeToFile(Set<Student> stus)throws IOException
{
BufferedWriter bw=new BufferedWriter(new FileWriter("d:/stu.txt"));
for(Student stu:stus)
{
bw.write(stu.toString());
bw.newLine();
bw.flush();
}
bw.close();
}
}
---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------