09_IO流
-
IO流用来处理设备之间的数据传输
-
Java对数据的操作时通过流的方式
-
Java用于操作流的对象都在IO包中
-
流按操作数据分为两种: 字节流和字符流
-
流按类型分为: 输入流, 输出流
|
1
2
3
4
5
6
7
8
|
//创建一个FileWriter对象,该文件会在指定目录下创建.如果同名则覆盖,除非构造方法第二个参数append 为 true; FileWriter fw = new FileWriter("d://abc.txt",false); fw.write("tiqiquxian"); //刷入目的地 fw.flush(); //关闭流对象,之前会flash一次缓冲中的数据. //与flush的区别: flush刷新后流可以继续使用,close却将流关闭,不可再写入 fw.close(); |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
//fw先为null,后赋值,finally中要分别对各个流进行捕获.FileWriter fw = null;try{ fw = new FileWriter("D:\\demo2.txt"); fw.write("我要\r\n换行了"); fw.flush();}catch(IOException e){ throw new RuntimeException("产生IO异常");}finally{ if(fw!=null) try{ fw.close(); } catch(IOException e){ throw new RuntimeException("流关闭异常"); }} |
|
1
2
3
4
|
int ch = 0; while((ch=fr.read())!=-1){ //relevant operation } |
|
1
2
3
4
5
|
int len= 0; char[] buf = new char[1024]; while((len=fr.read(buf))!=-1){ //relevant operation } |
|
1
2
3
4
|
String line = null; while((line=bfr.readLine())!=null){ System.out.println(line); } |
|
1
2
3
4
5
6
|
String line = null; while((line=bfr.readLine())!=null){ bfr.write(line); bfr.newLine(); bfr.flush(); } |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
//写方法 public static void write() throws IOException{ FileOutputStream fos = new FileOutputStream("d:\\tll.txt" ); fos.write( "awttwa".getBytes()); fos.close(); } public static void read1() throws IOException{ FileInputStream fis = new FileInputStream("d:\\tll.txt" ); int ch = 0; while((ch=fis.read())!=-1){ System.out.print((char)ch); } fis.close(); } public static void read2() throws IOException{ FileInputStream fis = new FileInputStream("d:\\tll.txt" ); int len = 0; byte[] buf = new byte[1024]; while((len=fis.read(buf))!=-1){ System.out.print(new String(buf,0,len)); } fis.close(); } //太取巧,还是read2比较好 public static void read3() throws IOException{ FileInputStream fis = new FileInputStream("d:\\tll.txt" ); byte[] buf = new byte[fis.available()]; fis.read(buf); System.out.print(new String(buf)); fis.close(); } //拷贝一个图片 public static void copyFile() throws IOException{ FileInputStream fis = new FileInputStream("d:\\kk.jpg" ); FileOutputStream fos = new FileOutputStream("d:\\mm.jpg" ); int len = 0; byte[] buf = new byte[1024]; while((len=fis.read(buf))!=-1){ fos.write(buf, 0, len); } fis.close(); fos.close(); } //使用字节流的缓冲区赋值一个MP3文件 public static void copyFile2() throws IOException{ BufferedInputStream bfis = new BufferedInputStream(new FileInputStream("D:\\M_Download\\我的音乐\\矜持.mp3" )); BufferedOutputStream bfos = new BufferedOutputStream(new FileOutputStream("d:\\jingchi.MP3" )); int len = 0; byte[] buf = new byte[1024]; while((len=bfis.read(buf))!=-1){ bfos.write(buf, 0, len); } bfis.close(); bfos.close(); } |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
//方法一: 传统思考 public static void method1() throws IOException{ InputStream in = System. in; StringBuilder sb = new StringBuilder(); int ch = 0; while(true ){ ch = in.read(); if(ch == '\r' ) continue; else if (ch == '\n' ){ String s = sb.toString(); if(s.equals("over" )) break; System. out.println(s); //清空缓冲区 sb.delete(0,sb.length()); } else sb.append(( char)ch); } } //方法二: InputStreamReader转换流,将字节流转成字符流的桥梁,然后经缓冲包装提高效率 public static void method2() throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in )); String line = null; while((line=in.readLine())!=null){ if(line.equals("over" )) break; System. out.println(line.toUpperCase()); } } |
|
1
2
3
|
osw.write(line); osw.newLine(); osw.flush(); |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
/* 1.创建当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件。System.out.println(f.createNewFile());最终目录的父目录必须存在,因此只是建立一层目录System.out.println(f.mkdir());可以任意建立多级目录System.out.println(f.mkdirs());*//* 2.删除boolean delete(); 删除失败返回falsevoid delectOnExit();在程序退出时删除指定文件*//* 3.判断boolean exists():文件是否存在,是最为常用的方法isFile();isDirectory();isHidden();isAbsolute(); *//* 4.获取getName();返回文件或目录名getPath();getParent();getAbsolutePath();lastModified();length();*/ |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
//5.列出指定目录下文件或文件夹,包含子目录中的内容. public static void listFile(File f,int level){ level++; if(f.isFile()) System.out.println(getLevel(level)+f); else if(f.isDirectory()){ System.out.println(getLevel(level)+f); File[] files = f.listFiles(); for(File file: files){ listFile(file,level); } }}public static String getLevel(int i){ StringBuilder sb = new StringBuilder(); for(int k=0;k<i;k++) sb.append("|-"); return sb.toString();} |
|
1
2
3
4
5
6
7
8
9
10
11
12
|
//6.删除一个带目录的内容public static void deleteDir(File f){ if(f.isFile()) f.delete(); else if(f.isDirectory()){ File[] files = f.listFiles(); for(File file: files){ deleteDir(file); } f.delete(); }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.util.ArrayList;import java.util.List;public class Demo2003listToFile { public static void main(String[] args) throws IOException { List<File> list = new ArrayList<File>(); //获取new下所有java文件,参数是目录和list对象 fileToList(new File("D:\\New"),list); //取出list对象中信息,并写入list.txt listToFile(list,new File("d:\\list.txt")); } //通过路径名,将所需信息存入list集合中 public static void fileToList(File f,List<File> list){ File[] files = f.listFiles(); for(File file:files){ if(file.isDirectory() && !file.isHidden()) fileToList(file,list); else if(file.isFile() && !file.isHidden()){ if(file.getName().endsWith(".java")) list.add(file); } } } //取出集合中所需信息,写入目标文件 public static void listToFile(List<File> list, File f){ BufferedWriter bfw = null; try{ bfw = new BufferedWriter(new FileWriter(f)); for(File file:list){ //getAbsolutePath方法是非常常用的,用来获取绝对路径 bfw.write(file.getAbsolutePath()); bfw.newLine(); bfw.flush(); } } catch(IOException e){ throw new RuntimeException("流写入异常"); } finally{ if(bfw!=null) try{ bfw.close(); } catch(IOException e){ throw new RuntimeException("流关闭异常"); } } } } |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//设置和获取元素 public static void set(){ Properties prop = new Properties(); prop.setProperty( "likai", "value1" ); prop. setProperty("tangl", "value2"); //System.out.println(prop); Set<String> set = prop.stringPropertyNames(); for(String key: set){ System. out.println(key+"___" +prop.getProperty(key)); } } |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
//方法一: 自定义将流中的数据存储到集合中: 1.一个流与info.txt关联 2.读一行,用'='进行切割 3.分别存入Properties中 public static void method1() throws IOException{ BufferedReader bfr = new BufferedReader(new FileReader( "D:\\hehe.txt")); Properties p = new Properties(); String line = null; while((line=bfr.readLine())!=null){ String[] sp = line.split( "="); p.setProperty(sp[0], sp[1]); } bfr.close(); System. out.println(p); } public static void method2() throws Exception{ Properties p = new Properties(); //一句话就载入了文件信息 p.load( new FileReader( "D:\\hehe.txt")); //以适合使用 load(Reader) 方法的格式,将此 Properties 表中的属性列表(键和元素对)写入输出字符。 p.setProperty("tangll", "kk" ); p.store(new FileWriter("D:\\hehe.txt" ), "by likai"); } |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
import java.io.*;import java.util.Properties;public class Demo2005ProPertiesApplication { public static void main(String[] args) throws Exception { File file = new File("D:\\K_Workspace\\SS\\times.txt"); if(!file.exists()) file.createNewFile(); FileReader fw = new FileReader(file); Properties p = new Properties(); p.load(fw); int t; String value = p.getProperty("times"); if(value == null) t = 1; else t = Integer.parseInt(value)+1; if(t>3){ System.out.println("该付款了,朋友!"); return; } p.setProperty("times", t+""); p.store(new FileWriter("D:\\K_Workspace\\SS\\times.txt"), "by alee"); }} |
|
1
2
3
4
5
6
7
8
9
|
//打印流的简单应用BufferedReader bfr = new BufferedReader( new InputStreamReader(System.in ));//设置自动刷新PrintWriter pw = new PrintWriter(System.out,true);String line = null;while((line=bfr.readLine())!=null){ //这样写比用BufferedWriter更简洁.PrintWriter确实更适合打印各种数据. pw.println(line);} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
//切割只用字节流,而不是字符流 public static void split() throws IOException{ FileInputStream fis = new FileInputStream("d:\\123.pdf" ); FileOutputStream fos = null; int len = 0; //1M=1024KB=1024*1024字节 存储 byte[] buf = new byte[1024*1024]; int i=0; while((len=fis.read(buf))!=-1){ fos = new FileOutputStream("d:\\" +(++i)+ ".part"); fos.write(buf, 0, len); fos.flush(); fos.close();; } fis.close(); } //文件合并 public static void meger() throws IOException{ Vector<FileInputStream> v = new Vector<FileInputStream> (); for(int i=1;i<4;i++) v.add( new FileInputStream("d:\\" + i+".part")); SequenceInputStream sis = new SequenceInputStream(v.elements()); FileOutputStream fos = new FileOutputStream("d:\\kk.pdf" ); int len = 0; byte[] buf = new byte[1024]; while((len=sis.read(buf))!=-1){ fos.write(buf, 0, len); } sis.close(); fos.close(); } |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
package itcast21;import java.io.*;public class Demo2101PipedStream { public static void main(String[] args) throws IOException { //建立管道读入流 PipedInputStream pis = new PipedInputStream(); //建立管道输出流并与读入流关联,也可以写成connect PipedOutputStream pos = new PipedOutputStream(pis); new Thread(new Write(pos)).start(); new Thread(new Read(pis)).start(); }}class Read implements Runnable{ private PipedInputStream pis; public Read(PipedInputStream pis){ this.pis = pis; } @Override public void run(){ byte[] buf = new byte[200]; try{ System.out.println("---读取流开始获取信息"); int len = pis.read(buf); System.out.println("--"+new String(buf,0,len)); System.out.println("---读取流读取流信息完毕"); }catch(IOException e){ throw new RuntimeException("流读取异常"); } finally{ if(pis!=null) try{pis.close();} catch(IOException e){ throw new RuntimeException("流关闭异常"); } } } }class Write implements Runnable{ private PipedOutputStream pos; public Write(PipedOutputStream pos){ this.pos = pos; } public void run(){ try { System.out.println("写入流开始写入流信息,持续3S"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } pos.write("Hello PipedStram".getBytes()); System.out.println("写入流开始写入完毕"); } catch (IOException e) { throw new RuntimeException("流写入异常"); } finally{ if(pos!=null) try{pos.close();} catch(IOException e){ throw new RuntimeException("流关闭异常"); } } }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
import java.io.*;import java.util.*;public class Demo2105Student { public static void main(String[] args) throws IOException { Set<Stu> set = getSet(); setToFile(set,new File("D:\\stud.txt")); } public static Set<Stu> getSet() throws IOException{ Set<Stu> set = new TreeSet<Stu>(new Comparator<Stu>(){ @Override public int compare(Stu o1, Stu o2) { int i= new Integer(o1.getSum()).compareTo(new Integer(o2.getSum())); if(i==0) return o1.getName().compareTo(o2.getName()); return i; } }); BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in)); String line = null; for(int i=0;i<3;i++){ line = bfr.readLine(); String[] info = line.split(","); set.add(new Stu(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[3]))); } return set; } public static void setToFile(Set<Stu> set, File f){ if(!f.exists()) try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } BufferedWriter bfw = null; try{bfw = new BufferedWriter(new FileWriter(f)); for(Stu stu: set){ bfw.write(stu.toString()); bfw.newLine(); bfw.flush(); } }catch(IOException e){ throw new RuntimeException("流异常"); } finally{ if(bfw != null) try{ bfw.close(); } catch(IOException e){ throw new RuntimeException("流关闭异常"); } } }}class Stu{ private String name; private int score1; private int score2; private int score3; private int sum; Stu(){} Stu(String name, int s1, int s2, int s3){ this.name = name; score1 = s1; score2 = s2; score3 = s3; sum = s1+s2+s3; } public String getName(){ return name; } public int getSum(){ return sum; } public String toString(){ return "姓名"+name+",分数"+sum; }} |

浙公网安备 33010602011771号