1 package com.transfar.vms.base.test;
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.FileNotFoundException;
7 import java.io.FileOutputStream;
8 import java.io.FileReader;
9 import java.io.FileWriter;
10 import java.io.IOException;
11 import java.io.InputStreamReader;
12 import java.io.OutputStreamWriter;
13 import java.io.PrintWriter;
14 import java.io.RandomAccessFile;
15
16 public class NewFileDemo {
17
18 public static void main(String[] args) throws IOException{
19 // 新建文件夹和文件
20 mkDirectory();
21 //读取文件
22 readFileContent();
23 //修改文件
24 modifyFileContent();
25 }
26 //读取文件的3种方式
27 private static void readFileContent() throws IOException {
28 // TODO Auto-generated method stub
29 FileReader fr = new FileReader("E://a//s//PLAYLIST.LY");// 内容为:Love lives,Love java!爱生活,爱java!
30 int ch = 0;
31 while ((ch = fr.read()) != -1) {
32 System.out.print((char) ch);
33 }
34
35 InputStreamReader isr = new InputStreamReader(new FileInputStream(
36 "E://a//s//PLAYLIST.LY"));
37 while ((ch = isr.read()) != -1) {
38 System.out.print((char) ch);
39 }
40
41 BufferedReader br = new BufferedReader(new InputStreamReader(
42 new FileInputStream("E://a//s//PLAYLIST.LY")));
43 String data = null;
44 while ((data = br.readLine()) != null) {
45 System.out.println(data);
46 }
47 fr.close();
48 isr.close();
49 br.close();
50 }
51 //新建文件夹以及文件
52 private static void mkDirectory() {
53 // TODO Auto-generated method stub
54 String mkDirectoryPath = "E:\\a\\s";
55 File file = null;
56 file = new File(mkDirectoryPath);
57 if (!file.exists()) {
58 file.mkdirs();
59 }
60 File writeFile = new File(mkDirectoryPath, "PLAYLIST.LY");
61 if(!writeFile.exists()){
62 try {
63 writeFile.createNewFile();
64 } catch (IOException e) {
65 // TODO Auto-generated catch block
66 e.printStackTrace();
67 }
68 }
69 }
70 /**
71 * 修改文件内容的三种方式
72 * @throws IOException
73 */
74 private static void modifyFileContent() throws IOException {
75
76 FileWriter fw = new FileWriter("E://a//s//PLAYLIST.LY");
77 String s = "Love lives, Love java!爱生活,爱java!";
78 fw.write(s, 0, s.length());
79 fw.flush();
80
81 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
82 "E://a//s//PLAYLIST.LY"));
83 osw.write(s, 0, s.length());
84 osw.flush();
85
86 PrintWriter pw = new PrintWriter(new OutputStreamWriter(
87 new FileOutputStream("E://a//s//PLAYLIST.LY")), true);
88 pw.println(s);
89
90 fw.close();
91 osw.close();
92 pw.close();
93 }
94 }