java中的IO流。
来源:互联网 发布:通达信编程视频教程 编辑:程序博客网 时间:2024/05/12 00:12
IO:
字符流的由来:
因为文件编码的不同,而有了对字符进行高效操作的字符流对象。
原理:其实就是基于字节流读取字节时,去查了指定的码表。
字节流和字符流的区别:
1,字节流读取的时候,读到一个字节就返回一个字节。字符流使用了字节流读到一个或多个字节(中文对应的字节数是两个,UTF-8 码表中是3 个字节)时。先去查指定的编码表,将查到的字符返回。
2,字节流可以处理所有类型数据,如图片,mp3,avi。而字符流只能处理字符数据。
结论:只要是处理纯文本数据,就要优先考虑使用字符流。除此之外都用节流。
3、实际上字节流在操作时本身不会用到缓冲区(内存),是文件本身直接操作的,而字符流在操作时使用了缓冲区,通过缓冲区再操作文件,如下图。
当指定绝对路径时,定义目录分隔符有两种方式:
1.反斜线但是一定要写两个。\\new FileWriter("c:\\demo.txt");
2.斜线/ 写一个即可。new FileWriter("c:/demo.txt");
3.输入的时候按byte[] byte = new byte[i]指定大小输入。输出的时候将字符串转化为byte b[] = str.getBytes() byte数组。
4.File的两个常量:File.separator 打印出为/ File.pathSeparator 打印出为:
File文件流:
File文件流直接调用new File的方法。具体如下:
新建或删除文件:
import java.io.*;class hello{ public static void main(String[] args) { File file=new File("D:\\hello.txt"); try{ file.方法名(); //file.createNewFile 创建一个新文件 //file.delete 删除一个文件 }catch (Exception e) { e.printStackTrace(); } }}
新建文件夹:
/** * 在d盘创建一个名字为hell的文件夹 * */import java.io.*;class hello{ public static void main(String[] args) { String fileName="D:"+File.separator+"hello"; File f=new File(fileName); f.mkdir(); }}
列出指定目录的全部文件(包括隐藏文件):
/** * 使用list列出指定目录的全部文件 * */import java.io.*;class hello{ public static void main(String[] args) { String fileName="D:"+File.separator; File f=new File(fileName); String[] str=f.list();//返回String数组是文件名的集合,如360Downloads,360,Program。 //File[] str = f.listFiles() 返回File类型的数组集合,得到具体的地址,如D:\360Downloads,D:\360,D:\Program等等 for(String str:fileNameList){ System.out.println(str); } }}
搜索指定目录的全部内容:
package com.xy.study.io.fileStream;import java.io.File;/** * description:递归方法列出一个目录中的所有内容 * @author 许阳 */public class listAllFileOfPath { public File print(File file){ if(file!=null){ File[] files = file.listFiles(); for(File file1: files){ if(file1.isDirectory()){ print(file1); }else{ System.out.println(file1); } } } return null; } public static void main(String [] args){ String filePath = "D:/"; File file = new File(filePath); new listAllFileOfPath().print(file); }}
字节流:
向文件写入字符串:
public class outputStringToFile { public static void main(String [] args){ String filePath = "d:"+ File.separator+"test.txt"; File file = new File(filePath); try{ OutputStream outputStream = new FileOutputStream(file);//FileOutputStream(file,true) 向文件追加内容。 //FileOutStream是OutputStream接口的一个具体实现,具体可看最上面的示意图。 String str = "Hello World,Hello Java!";//String str = "\r\n"是换行的意思 byte[] bytes = str.getBytes(); outputStream.write(bytes); outputStream.close(); }catch (Exception e){ e.printStackTrace(); } }}
从文件中读取内容:
public class inputStringFromFile { public static void main(String [] args){ String path = "d:"+ File.separator+"test.txt"; File file = new File(path); try { InputStream inputStream = new FileInputStream(file); byte[] bytes = new byte[1024];//byte[] b=new byte[(int)file.length()];指定一次性读取所有内容。避免设定的大小或者太小。 int len; if((len=inputStream.read(bytes))!=-1){//查看文件是否读到了末尾,若是,返回-1 System.out.println("读取的长度为"+len); System.out.print(new String(bytes,0,len)); }else{ inputStream.close(); } } catch (Exception e) { e.printStackTrace(); } }}
字符流:
向文件中写内容:
public class writeStringToFile { public static void main(String [] args) { String filePath = "d:"+File.separator+"test.txt"; File file = new File(filePath); try { Writer writer = new FileWriter(file);//Writer out =new FileWriter(f,true);向文件中追加内容。 String str = "雄关漫道真如铁,而今迈步从头越。"; writer.write(str); writer.close(); } catch (IOException e) { e.printStackTrace(); } }}
从文件中读取内容:
public class readStringFromFile { public static void main(String [] args) { String filePath = "d:"+ File.separator+"test.txt"; File file = new File(filePath); try { Reader reader = new FileReader(file); char[] chars = new char[100]; int len; if((len = reader.read(chars))!=-1){ System.out.println("读取的长度为"+len); System.out.print(new String(chars,0,len)); } reader.close(); } catch (IOException e) { e.printStackTrace(); } }}
BufferedReader读取键盘录入并输出到某文件:
public class BufferedReaderInputSystemIn { public static void main(String [] args) throws Exception{ File file = new File("d:"+File.separator+"test.txt"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); String str = null; System.out.println("请输入内容:"); System.setOut(new PrintStream(new FileOutputStream(file))); str = bufferedReader.readLine(); System.out.println(str); }}
字节流和字符流的互相转换:
整个IO类中除了字节流和字符流还包括字节和字符转换流。
OutputStreramWriter将输出的字节流转化为字符流。
InputStreamReader将输入的字节流转换为字符流。
将字节输出流转化为字符输出流
public class fileOutputStreamToOutputStreamWriter { public static void main(String [] args){ File file = new File("d:"+File.separator+"test.txt"); try { Writer writer = new OutputStreamWriter(new FileOutputStream(file)); writer.write("hello"); writer.close(); } catch (Exception e) { e.printStackTrace(); } }}
将字节输入流变为字符输入流
public class fileInputStreamToInputStreamReader { public static void main(String[] args){ String filePath = "d:"+ File.separator+"test.txt"; try { Reader reader = new InputStreamReader(new FileInputStream(filePath)); char[] chars = new char[1024]; int len; if((len=reader.read(chars))!=-1){ System.out.println(new String(chars,0,len)); } } catch (Exception e) { e.printStackTrace(); } }}
内存流
ByteArrayOutputStream类是在创建它的实例时,程序内部创建一个byte型别数组的缓冲区,然后利用ByteArrayOutputStream和ByteArrayInputStream的实例向数组中写入或读出byte型数据。在网络传输中我们往往要传输很多变量,我们可以利用ByteArrayOutputStream把所有的变量收集到一起,然后一次性把数据发送出去。
ByteArrayOutputStream: 可以捕获内存缓冲区的数据,转换成字节数组。
ByteArrayInputStream:可以将字节数组转化为输入流。//使用内存流将字符串读入转换成小写字母然后输出public class byteArrayChangeString { public static void main(String [] args){ String str = "XUYANG"; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes()); int len ; while((len=inputStream.read())!=-1){ char ch = (char)len; outputStream.write(Character.toLowerCase(ch)); } String outStr = outputStream.toString(); try { inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println(outStr); }}
管道流
管道流主要可以进行两个线程之间的通信。
管道发送类:
public class MessageSend implements Runnable{ private PipedOutputStream outputStream = null; public MessageSend(){ outputStream = new PipedOutputStream(); } public PipedOutputStream getOutputStream(){ return this.outputStream; } @Override public void run() { String message = "Hello World,Hello Java!"; byte[] bytes = message.getBytes(); try { outputStream.write(bytes); } catch (IOException e) { e.printStackTrace(); } try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } }}管道接收类:
public class MessageReceive implements Runnable { private PipedInputStream inputStream = null; public MessageReceive(){ inputStream = new PipedInputStream(); } public PipedInputStream getInputStream(){ return this.inputStream; } @Override public void run() { byte[] bytes = new byte[1000]; int len; try { if((len = inputStream.read(bytes))!=-1){ System.out.println("接收的内容为"+new String(bytes,0,len)); } } catch (IOException e) { e.printStackTrace(); } try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } }}测试类:
public class PipedStreamSocket { public static void main(String [] args){ MessageSend messageSend = new MessageSend(); MessageReceive messageReceive = new MessageReceive(); //连接管道 try { messageSend.getOutputStream().connect(messageReceive.getInputStream()); } catch (IOException e) { e.printStackTrace(); } new Thread(messageSend).start(); new Thread(messageReceive).start(); }}
打印流(Print):
向文件输入字符串:
public class PrintStringToFile{ public static void main(String [] args) throws Exception{ PrintStream printStream = new PrintStream(new FileOutputStream(new File("d:"+File.separator+"test.txt"))); String str = "雄关漫道真如铁,而今迈步从头越!"; //byte[] bytes = str.getBytes(); 不能转化成字节打印,否则是乱码。 printStream.println(str); printStream.close(); }}
输出重定向:
输出字符串重定向:
public class PrintStringRedirect { public static void main(String[] args) throws Exception{ System.out.println("这些在控制台可以看到"); OutputStream outputStream = new FileOutputStream(new File("D:"+File.separator+"test.txt")); System.setOut(new PrintStream(outputStream)); System.out.println("这些在文件中才能看到"); }}
输出错误信息重定向:
自定义一个异常:
public class myException extends Exception { public myException(int i){ super("您输入的数为"+i); }}异常重定向:
public class PrintErrorRedirect { public static void main(String [] args) throws Exception{ System.err.println("这些在控制台可以看到"); PrintStream printStream = new PrintStream(new FileOutputStream(new File("d:"+File.separator+"test.txt"))); System.setErr(printStream); int i = 10; if(i>0){ throw new MyException(i); } }}这样就可以在指定的文件里读取到一堆的异常信息了。
输入重定向:
//从文件读取内容而不从键盘录入public class SystemInRedirect { public static void main(String[] args) throws Exception{ File file = new File("d:"+File.separator+"test.txt"); System.setIn(new FileInputStream(file)); byte[] bytes = new byte[1024]; int len; if((len=System.in.read(bytes))!=-1){ System.out.println(new String(bytes,0,len)); } }}
扫描流:
扫描流读取键盘输入:
public class ScannerReadSystemIn { public static void main(String [] args){ Scanner scanner = new Scanner(System.in); System.out.println("请输入:"); String a = scanner.next(); //int a = scanner.nextInt();整数型 //long a = scanner.nextLong();长整型 System.out.println(a); }}其他:
Scanner(File source)
构造一个新的Scanner
,它生成的值是从指定文件扫描的。
Scanner(InputStream source)
构造一个新的Scanner
,它生成的值是从指定的输入流扫描的。
数据流:
数据流写入char数组到文件并读取出来:
public class DataOutputStreamWriteStringToFile { public static void main(String[] args) throws Exception{ File file = new File("d:"+File.separator+"test.txt"); DataOutputStream outputStream = new DataOutputStream(new FileOutputStream(file)); DataInputStream inputStream = new DataInputStream(new FileInputStream(file)); char[] chars = {'A','B','C'}; for(char temp:chars){ outputStream.writeChar(temp); } char[] ch = new char[10]; int count= 0 ; char temp; while((temp = inputStream.readChar()) != 'C'){ ch[count++] = temp; } System.out.println(ch); }}
合并流:
读取两个文件,合并在一起输出到另外一个文件:
public class SequenceFile { public static void main(String [] args) throws Exception{ File file1 = new File("d:"+File.separator+"test.txt"); File file2 = new File("d:"+File.separator+"hello.txt"); File file3 = new File("d:"+File.separator+"xuyang.txt"); InputStream input1 = new FileInputStream(file1); InputStream input2 = new FileInputStream(file2); OutputStream output = new FileOutputStream(file3); //合并流 SequenceInputStream sequenceInputStream = new SequenceInputStream(input1,input2);//合并在一起读出来,根据参数顺序读取 int len = 0 ; while((len = sequenceInputStream.read())!=-1){ output.write(len); } input1.close(); input2.close(); }}
压缩流:
压缩文件:
压缩单个文件:
public class zipOutputStreamFile { public static void main(String [] args) throws Exception{ File file = new File("d:"+File.separator+"test.txt"); File zipFile = new File("d:"+File.separator+"test.zip"); ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); InputStream inputStream = new FileInputStream(file); //开始写入新的 ZIP 文件条目并将流定位到条目数据的开始处。 zipOut.putNextEntry(new ZipEntry(file.getName())); //添加注释 zipOut.setComment("test"); int len ; while((len=inputStream.read())!=-1){ zipOut.write(len); } inputStream.close(); zipOut.close(); }}
压缩多个文件:
public class ZipOutputStreamManyFile { public static void main(String [] args) throws Exception{ File file = new File("d:"+File.separator+"123"); File zipFile = new File("d:"+File.separator+"123.zip"); ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); zipOut.setComment("测试!"); InputStream inputStream = null; if(file.isDirectory()){ File[] files = file.listFiles(); for(File file1:files){ inputStream = new FileInputStream(file1); zipOut.putNextEntry(new ZipEntry(file1.getName())); int len; while((len=inputStream.read())!=-1){ zipOut.write(len); } inputStream.close(); } } zipOut.close(); }}
解压文件:
解压单个文件:
public class UnZipInputStreamFile { public static void main(String [] args) throws Exception{ File file = new File("d:"+File.separator+"test.zip"); File unFile = new File("d:"+File.separator+"test.txt"); //说明是个压缩文件 ZipFile zipFile = new ZipFile(file); //打印要压缩文件的名字 System.out.println(zipFile.getName()); InputStream input = zipFile.getInputStream(zipFile.getEntry("test.txt"));//指定要压缩包内的文件名 OutputStream output = new FileOutputStream(unFile); int len; while((len=input.read())!=-1){ output.write(len); } output.close(); input.close(); }}解压多个文件(需要用到ZipInputStream流):
public class UnZipInputStreamManyFile { public static void main(String [] args) throws Exception{ File file = new File("d:"+File.separator+"123.zip"); File outFile = null; //指定是一个zip文件 ZipFile zipFile = new ZipFile(file); ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file)); ZipEntry entry = null; InputStream inputStream = null; OutputStream outputStream = null; while ((entry = zipInput.getNextEntry())!=null){ outFile = new File("d:"+File.separator+ entry.getName()); if(!outFile.getParentFile().exists()){ outFile.getParentFile().mkdir(); } if(!outFile.exists()){ outFile.createNewFile(); } inputStream = zipFile.getInputStream(entry); outputStream = new FileOutputStream(outFile); int temp ; if((temp = inputStream.read())!=-1){ outputStream.write(temp); } inputStream.close(); outputStream.close(); } }}
回退流:
public class pushBackInputSteamTest { public static void main(String [] args) throws Exception{ String str = "Hello,Java!"; PushbackInputStream push = null; ByteArrayInputStream byteArray = new ByteArrayInputStream(str.getBytes()); push = new PushbackInputStream(byteArray); int temp = 0; while((temp = push.read())!=-1){ if(temp==','){ push.unread(temp); temp=push.read(); System.out.print("(回退"+(char)temp +")"); }else{ System.out.print((char)temp); } } }}//打印出来为Hello(回退,)Java!
编码:
乱码的产生:
public class ErrorEncoding { public static void main(String [] args) throws Exception{ String str = "上帝请保佑许阳"; //System.getProperty("file.encoding")获取本地编码 byte[] bytes = str.getBytes("ISO8859-1"); OutputStream out = new FileOutputStream(new File("d:"+File.separator+"test.txt")); out.write(bytes); out.close(); }}//乱码是由于编码不一致造成的
对象流:
对象流只能将支持 java.io.Serializable 接口的对象写入流中。
对象序列化就是把一个对象变为二进制数据流的一种方法。
一个类要想被序列化,就行必须实现java.io.Serializable接口。虽然这个接口中没有任何方法,就如同之前的cloneable接口一样。实现了这个接口之后,就表示这个类具有被序列化的能力。
可序列化的类:
public class Persion implements Serializable { private String name ; private int age; public Persion (){ } public Persion (String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "姓名:"+name+",年龄:"+age; }}用ObjectOutputStream流向文件写入object:
public class objectOutputStreamDemo { public static void main(String[] args) throws IOException { File file = new File("d:" + File.separator + "test.txt"); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream( file)); oos.writeObject(new Person("许阳",22)); oos.close(); }}此时查看的时候是乱码。因为是二进制的。可以使用ObjectInputStream读取。
public class ObjectInputStreamDemo{ public static void main(String[] args) throws Exception{ File file = new File("d:" + File.separator + "test.txt"); ObjectInputStream input = new ObjectInputStream(new FileInputStream( file)); Object obj = input.readObject(); input.close(); System.out.println(obj); }}此时显示的是:姓名:许阳,年龄:22
自定义序列化:
public class ExternalizableDemo{ public static void main(String[] args) throws Exception{ ser(); // 序列化 dser(); // 反序列话 } public static void ser() throws Exception{ File file = new File("d:" + File.separator + "test.txt"); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream( file)); out.writeObject(new Person("许阳", 23)); out.close(); } public static void dser() throws Exception{ File file = new File("d:" + File.separator + "test.txt"); ObjectInputStream input = new ObjectInputStream(new FileInputStream( file)); Object obj = input.readObject(); input.close(); System.out.println(obj); }} class Person implements Externalizable{ public Person(){ } public Person(String name, int age){ this.name = name; this.age = age; } @Override public String toString(){ return "姓名:" + name + " 年龄:" + age; } // 复写这个方法,根据需要可以保存的属性或者具体内容,在序列化的时候使用 @Override public void writeExternal(ObjectOutput out) throws IOException{ out.writeObject(this.name); out.writeInt(age); } // 复写这个方法,根据需要读取内容 反序列话的时候需要 @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException{ this.name = (String) in.readObject(); this.age = in.readInt(); } //private transient String name; 加了transient属性代表此属性对应的数据显示为null private String name; private int age;}
- JAVA 中的IO流
- JAVA 中的IO流
- Java中的IO流
- JAVA 中的IO流
- JAVA 中的IO流
- JAVA 中的IO流
- JAVA 中的IO流
- java中的io流
- JAVA 中的IO流
- JAVA 中的IO流
- java中的io流
- java中的IO流。
- java中的io流
- java中的IO流
- java中的IO流
- Java中的IO流
- java中的IO流
- java中的IO流
- WordPress上传中文文件名或图片名乱码问题
- linux 无线上网(network manager+wpa_supplicant )
- svn自动从主干合入代码到分支bat命令
- [MinGW]_[C/C++]_[msys的使用问题]
- 将Sublime Text 2搭建成一个好用的IDE
- java中的IO流。
- 创建sql server 分区表实例
- 机器学习实战中的问题汇总
- AlertDialog与acivity的交互
- 高性能 Windows Socket 组件 HP-Socket v2.3.1-beta-2 发布
- Sublime Text 2 - 性感无比的代码编辑器!程序员必备神器!跨平台支持Win/Mac/Linux
- 图解windows系统 硬盘主分区、扩展分区、逻辑分区的区别.
- iOS编程——多态
- atomic_cmpxchg