Java IO 基礎學習

學習Java有段時間了,但總感覺缺少點什麼,思考下感覺把自己喜歡的部分總結並分享下會好很多。後期有新內容還會繼續更新。

基礎類(都是抽象類):
字節byte <-> InputStream & OutputStream
字符char <-> Reader & Writer.


對於調用關係自己粗略的整理了下,如上圖。

Java採用靈巧的方式分離了這樣兩種機制。
直接調用filename或File的有 FileInputStream, OutputStream, FileReader, FileWriter, PrintWrite等其他的將字節或字符進行組裝來使用,例如BufferedReader, BufferedInputStream等。

IO中最主要的還是如何使用,本人收集了一些基本分析及使用。
========================================================
Example 二進制文件讀與寫
String data = "hello world";
byte[] bs = new byte[128];
System.out.println("Write data : " + data);
try (FileOutputStream out = new FileOutputStream(path)) {
	out.write(data.getBytes());
} catch (IOException e) {
	e.printStackTrace();
}		
try (FileInputStream fin = new FileInputStream(path)) {			
	fin.read(bs, 0, bs.length);
	System.out.println(bs.toString());
} catch (IOException e) {
	e.printStackTrace();
}		
try (DataInputStream din = new DataInputStream(new FileInputStream(path))) {
	byte b = din.readByte();
	System.out.println(b);
} catch (Exception e) {
	e.printStackTrace();
}
===========================================================

Example 2. zip文件的讀與寫。zip文件的處理:ZipInputStream, ZipOutputStream, ZipEntry. 他們也不是和文件直接打交道,而主要是處理字節流。

try {    
	byte[] buffer = new byte[4096];
	int length;
	ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(fileZipFile));
	ZipEntry zipEntry = zipInputStream.getNextEntry();
	while (zipEntry != null) {
		String fileName = zipEntry.getName();
		File newFile = new File(outputDir + File.separator + fileName);
		if (zipEntry.isDirectory())
			newFile.mkdirs();
		else {
			new File(newFile.getParent()).mkdirs();
			FileOutputStream fileOutputStream = new FileOutputStream(newFile);
			while ((length = zipInputStream.read(buffer)) > 0)
				fileOutputStream.write(buffer, 0, length);
			fileOutputStream.close();   
		}
		zipEntry = zipInputStream.getNextEntry();
	}
	zipInputStream.closeEntry();
	zipInputStream.close();
} catch (IOException e) {
        e.printStackTrace();
}


try(ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfilename)))  {
	for (int i = 0; i < fileList.size(); i++) {
		FileInputStream fis = new FileInputStream(fileList.get(i));
		out.putNextEntry(new ZipEntry(fileList.get(i).getName()));
		int len;
		while ((len = fis.read(buffer)) > 0) {
			out.write(buffer, 0, len);
		}
		out.closeEntry();
		fis.close();
	}
} catch (Exception e) {
	e.printStackTrace();
} 
================================================================
Example 3: 從字節到字符的的轉換,主要是InputStreamReader和OutputStreamWriter.
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = br.readLine();

String data = "hello world";
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(data, 0, data.length());

Scanner in = new Scanner(new InputStreamReader(new FileInputStream(file)));
data = in.nextLine();

PrintWriter pw = new PrintWriter("data.txt");
pw.print("name");
pw.println("next line");
==============================================================
Example 4: 深度拷貝。
public static Object deepClone(Object object) {
        Object clonedObject = null;        
        try {	
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
	     // read byte.
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            clonedObject = ois.readObject();
        }
        catch (Exception e) {
            logger.error("", e);
        }
        return clonedObject;
    }
============================================================
Java SE7 後增加了Path 和 Files 類。用處很多
Path absolute = Paths.get("/home", "cat");
Path relative = Paths.get("myprog", "conf", "user.properties");

byte[] bytes = Files.readAllBytes(path);
String content = new String(bytes, charset);
List<String> lines = Files.readAllLines(path, charset);
Files.write(path, conent.getBytes());
Files.write(path, lines);
InputStream in = Files.newInputStream(path);
OutputStream out = Files.newOutputStream(path);
Reader in = Files.newBufferedReader(path, charset);
Writer out = Files.newBufferedWriter(path, charest);
// copy and move
Files.copy(frompath, topath);
Files.move(frompath, topath);
Files.deleteIfExists(path);
Files.createFile(path);
Files.createDirectory(path);

// 例如查找文件。
 Path path = Paths.get("D:\\Summary\\Jave_Web");
 try (DirectoryStream<Path> entries = Files.newDirectoryStream(path, "*.pdf")) {
	for(Path entry : entries) {
		System.out.println(entry.getFileName());
}
  } catch (Exception e) {
	e.printStackTrace();
  }
後續繼續增加各種應用。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章