学习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();
}
后续继续增加各种应用。