一、輸入和輸出
1.基礎知識
(1)任何來自 InputStream ,Reader派生的類都含有 read() 方法。
任何來自OutputStream,Writer 派生的類都含有 writer()方法。
(2)創建單一的結果流,需要創建多個對象來修飾結果流。
(3)Java I/O類庫需要多種不同功能的組合。
(4)幾乎每次都要對輸入進行緩衝。
2.對IO系統整體瞭解
參考博客:http://blog.csdn.net/yhaolpz/article/details/68945336
3.典型使用
(1)緩衝輸入文件
/**
* 讀取文件:
* 1.採用字符輸入
* 2.可以使用以 String 或者 File 作爲文件名的 FileInputStrean
* 3.爲了提高速度,需要進行緩衝
* 4.採用 readLine() 方法,讀取文件內容。
*/
public class BufferedInputFile {
public static String read(String fileName) {
try {
BufferedReader in = new BufferedReader(new FileReader(fileName));
String str;
StringBuilder sb = new StringBuilder();
try {
while ((str = in.readLine()) != null) {
sb.append(str + "\n");
}
in.close();
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws IOException{
System.out.println(read("F:\\manage\\javase2\\src\\main\\resources\\app.js"));
}
}
(2)緩衝輸入文件練習
/**
* 打開一個文件,將讀取的每行數據存儲到 LinkedList 中,然後倒序輸出。
*/
public class Test01 {
public static List<String> read(String fileName) {
try {
BufferedReader in = new BufferedReader(new FileReader(fileName));
List<String> lineList = new LinkedList<String>();
String str;
try {
while ((str = in.readLine()) != null) {
lineList.add(str);
}
in.close();
return lineList;
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws IOException {
List<String> linkedList = read("F:\\manage\\javase2\\src\\main\\resources\\app.js");
/*Iterator iterator = linkedList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}*/
int length = linkedList.size();
for (int i = length - 1; i >= 0; i--) {
System.out.println(linkedList.get(i));
}
}
}
(3)從內存輸入
read()方法返回int類型,需要轉化爲 char 類型。
/**
* 從內存輸入
*/
public class Test02 {
public static void main(String[] args) {
String str = BufferedInputFile.read("F:\\manage\\javase2\\src\\main\\resources\\app.js");
if (str != null) {
StringReader in = new StringReader(str);
int c;
try {
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}