java文件读写

1、按字节读取文件内容

2、按字符读取文件内容

3、按行读取文件内容

4、随机读取文件内容

  1 public class ReadFromFile {
  2     /**
  3      * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
  4      */
  5     public static void readFileByBytes(String fileName) {
  6         File file = new File(fileName);
  7         InputStream in = null;
  8         try {
  9             System.out.println("以字节为单位读取文件内容,一次读一个字节:");
 10             // 一次读一个字节
 11             in = new FileInputStream(file);
 12             int tempbyte;
 13             while ((tempbyte = in.read()) != -1) {
 14                 System.out.write(tempbyte);
 15             }
 16             in.close();
 17         } catch (IOException e) {
 18             e.printStackTrace();
 19             return;
 20         }
 21         try {
 22             System.out.println("以字节为单位读取文件内容,一次读多个字节:");
 23             // 一次读多个字节
 24             byte[] tempbytes = new byte[100];
 25             int byteread = 0;
 26             in = new FileInputStream(fileName);
 27             ReadFromFile.showAvailableBytes(in);
 28             // 读入多个字节到字节数组中,byteread为一次读入的字节数
 29             while ((byteread = in.read(tempbytes)) != -1) {
 30                 System.out.write(tempbytes, 0, byteread);
 31             }
 32         } catch (Exception e1) {
 33             e1.printStackTrace();
 34         } finally {
 35             if (in != null) {
 36                 try {
 37                     in.close();
 38                 } catch (IOException e1) {
 39                 }
 40             }
 41         }
 42     }
 43 
 44     /**
 45      * 以字符为单位读取文件,常用于读文本,数字等类型的文件
 46      */
 47     public static void readFileByChars(String fileName) {
 48         File file = new File(fileName);
 49         Reader reader = null;
 50         try {
 51             System.out.println("以字符为单位读取文件内容,一次读一个字节:");
 52             // 一次读一个字符
 53             reader = new InputStreamReader(new FileInputStream(file));
 54             int tempchar;
 55             while ((tempchar = reader.read()) != -1) {
 56                 // 对于windows下,
这两个字符在一起时,表示一个换行。
 57                 // 但如果这两个字符分开显示时,会换两次行。
 58                 // 因此,屏蔽掉
,或者屏蔽
。否则,将会多出很多空行。
 59                 if (((char) tempchar) != '
') {
 60                     System.out.print((char) tempchar);
 61                 }
 62             }
 63             reader.close();
 64         } catch (Exception e) {
 65             e.printStackTrace();
 66         }
 67         try {
 68             System.out.println("以字符为单位读取文件内容,一次读多个字节:");
 69             // 一次读多个字符
 70             char[] tempchars = new char[30];
 71             int charread = 0;
 72             reader = new InputStreamReader(new FileInputStream(fileName));
 73             // 读入多个字符到字符数组中,charread为一次读取字符数
 74             while ((charread = reader.read(tempchars)) != -1) {
 75                 // 同样屏蔽掉
不显示
 76                 if ((charread == tempchars.length)
 77                         && (tempchars[tempchars.length - 1] != '
')) {
 78                     System.out.print(tempchars);
 79                 } else {
 80                     for (int i = 0; i < charread; i++) {
 81                         if (tempchars[i] == '
') {
 82                             continue;
 83                         } else {
 84                             System.out.print(tempchars[i]);
 85                         }
 86                     }
 87                 }
 88             }
 89 
 90         } catch (Exception e1) {
 91             e1.printStackTrace();
 92         } finally {
 93             if (reader != null) {
 94                 try {
 95                     reader.close();
 96                 } catch (IOException e1) {
 97                 }
 98             }
 99         }
100     }
101 
102     /**
103      * 以行为单位读取文件,常用于读面向行的格式化文件
104      */
105     public static void readFileByLines(String fileName) {
106         File file = new File(fileName);
107         BufferedReader reader = null;
108         try {
109             System.out.println("以行为单位读取文件内容,一次读一整行:");
110             reader = new BufferedReader(new FileReader(file));
111             String tempString = null;
112             int line = 1;
113             // 一次读入一行,直到读入null为文件结束
114             while ((tempString = reader.readLine()) != null) {
115                 // 显示行号
116                 System.out.println("line " + line + ": " + tempString);
117                 line++;
118             }
119             reader.close();
120         } catch (IOException e) {
121             e.printStackTrace();
122         } finally {
123             if (reader != null) {
124                 try {
125                     reader.close();
126                 } catch (IOException e1) {
127                 }
128             }
129         }
130     }
131 
132     /**
133      * 随机读取文件内容
134      */
135     public static void readFileByRandomAccess(String fileName) {
136         RandomAccessFile randomFile = null;
137         try {
138             System.out.println("随机读取一段文件内容:");
139             // 打开一个随机访问文件流,按只读方式
140             randomFile = new RandomAccessFile(fileName, "r");
141             // 文件长度,字节数
142             long fileLength = randomFile.length();
143             // 读文件的起始位置
144             int beginIndex = (fileLength > 4) ? 4 : 0;
145             // 将读文件的开始位置移到beginIndex位置。
146             randomFile.seek(beginIndex);
147             byte[] bytes = new byte[10];
148             int byteread = 0;
149             // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
150             // 将一次读取的字节数赋给byteread
151             while ((byteread = randomFile.read(bytes)) != -1) {
152                 System.out.write(bytes, 0, byteread);
153             }
154         } catch (IOException e) {
155             e.printStackTrace();
156         } finally {
157             if (randomFile != null) {
158                 try {
159                     randomFile.close();
160                 } catch (IOException e1) {
161                 }
162             }
163         }
164     }
165 
166     /**
167      * 显示输入流中还剩的字节数
168      */
169     private static void showAvailableBytes(InputStream in) {
170         try {
171             System.out.println("当前字节输入流中的字节数为:" + in.available());
172         } catch (IOException e) {
173             e.printStackTrace();
174         }
175     }
176 
177     public static void main(String[] args) {
178         String fileName = "C:/temp/newTemp.txt";
179         ReadFromFile.readFileByBytes(fileName);
180         ReadFromFile.readFileByChars(fileName);
181         ReadFromFile.readFileByLines(fileName);
182         ReadFromFile.readFileByRandomAccess(fileName);
183     }
184 }
View Code

5、将内容追加到文件尾部

 1 public class AppendToFile {
 2     /**
 3      * A方法追加文件:使用RandomAccessFile
 4      */
 5     public static void appendMethodA(String fileName, String content) {
 6         try {
 7             // 打开一个随机访问文件流,按读写方式
 8             RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
 9             // 文件长度,字节数
10             long fileLength = randomFile.length();
11             //将写文件指针移到文件尾。
12             randomFile.seek(fileLength);
13             randomFile.writeBytes(content);
14             randomFile.close();
15         } catch (IOException e) {
16             e.printStackTrace();
17         }
18     }
19 
20     /**
21      * B方法追加文件:使用FileWriter
22      */
23     public static void appendMethodB(String fileName, String content) {
24         try {
25             //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
26             FileWriter writer = new FileWriter(fileName, true);
27             writer.write(content);
28             writer.close();
29         } catch (IOException e) {
30             e.printStackTrace();
31         }
32     }
33 
34     public static void main(String[] args) {
35         String fileName = "C:/temp/newTemp.txt";
36         String content = "new append!";
37         //按方法A追加文件
38         AppendToFile.appendMethodA(fileName, content);
39         AppendToFile.appendMethodA(fileName, "append end. 
");
40         //显示文件内容
41         ReadFromFile.readFileByLines(fileName);
42         //按方法B追加文件
43         AppendToFile.appendMethodB(fileName, content);
44         AppendToFile.appendMethodB(fileName, "append end. 
");
45         //显示文件内容
46         ReadFromFile.readFileByLines(fileName);
47     }
48 }
View Code
原文地址:https://www.cnblogs.com/linbo3168/p/8000050.html