首页 > 程序开发 > 软件开发 > Java >

Java IO 基础学习 - 基础类(都是抽象类)

2018-04-11

Java IO 基础学习 - 基础类(都是抽象类)。

Java IO 基础学习 - 基础类(都是抽象类)。

基础类(都是抽象类):
字节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 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 entries = Files.newDirectoryStream(path, "*.pdf")) {
	for(Path entry : entries) {
		System.out.println(entry.getFileName());
}
  } catch (Exception e) {
	e.printStackTrace();
  }
相关文章
最新文章
热点推荐