JAVA语言 IO 基础学习 - 基础类(都是抽象类)
小标 2019-01-09 来源 : 阅读 994 评论 0

摘要:本文主要向大家介绍了JAVA语言 IO 基础学习 - 基础类(都是抽象类),通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。

本文主要向大家介绍了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();

  }</path></string>

   


          

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注编程语言JAVA频道!


本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程