File文件的相关练习

文件操作的三种方式:

    public static void main(String[] args) {
//用File表示D:/IoFile/File/File.txt
File f1 = new File("D:/IoFile/File/File.txt");
File f2 = new File("D:/IoFile/File","File.txt");
//文件夹
File parent = new File("D:/IoFile/File");
//文件
File f3 = new File(parent,"File.txt");
}

文件的相关方法练习:

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("输入一个文件路径,显示文件的相关属性:");
String str1 = sc.next();
File f1 = new File(str1);
//文件是否存在
System.out.println("文件存在?:"+f1.exists());
//读写属性
System.out.println("可读?;"+f1.canRead());
System.out.println("可写?:"+f1.canWrite());
//是否是目录
System.out.println("是否是目录:"+f1.isDirectory());
//文件的绝对路径
System.out.println("文件的绝对路径为:"+f1.getAbsolutePath());
//文件的上级文件
System.out.println("文件的上级文件为:"+f1.getParent());
}

文件创建、删除操作:

public static void main(String[] args) {
//创建文件
File file = new File("D:/IoFile/File/dir1/dir2");
//创建普通文件
// try {
// file.createNewFile();
// System.out.println("文件创建成功!");
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//创建文件夹
// file.mkdir();
// System.out.println("文件夹创建成功!"); //mkdirs 递归创建文件夹
File file1 = new File("D:/IoFile/File/File/File/file");
System.out.println(file1.mkdirs()); //在D:/iodemo/abc/def下创建一个文件a.txt
File parent = new File("D:/iodemo/abc/def");
File a = new File(parent,"a.txt");
//判断文件夹是否存在
if(!parent.exists()){
//不存在先创建文件夹
parent.mkdirs();
}
try {
//文件创建成功
a.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

文件练习:

输出一个文件夹中的所有文件、普通文件、以及文件夹的大小。

public static void main(String[] args) {
String str = "D:/IoFile/File";
File f = new File(str);
int count=0;
int totalsize=0;
if(f.exists()){
File[] files = f.listFiles();
System.out.println("所有文件个数是:"+files.length);
//循环遍历所有文件
for(int i = 0;i<files.length;i++){
if(files[i].isFile()){
//普通文件个数
count++;
//文件大小
//文件夹没有大小,若文件夹里有文件,则文件夹大小为文件大小之和
totalsize+=files[i].length();
}
}
System.out.println("普通文件个数是:"+count);
System.out.println("所有文件大小是:"+(float)totalsize/1024+"kb");
}else{
System.out.println("该文件夹不存在!");
}
}

FileReader读取文件

public static void main(String[] args) {
//读取文件
File f = new File("D:/IoFile/File/fileReader.txt");
FileReader fr=null;
try {
fr = new FileReader(f);
char[] c = new char[1024];
int len=0;
StringBuffer sb= new StringBuffer();
while((len=fr.read(c,0,10))!=-1){
//把读取到的内容存放到sb中
sb.append(c,0,len);
}
System.out.println(sb.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(fr!=null) {
fr.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

读取文件逐行读取

        //读取文件
File f = new File("D:/IoFile/File/fileReader.txt");
FileReader fr=null;
BufferedReader br = null; fr = new FileReader(f);
br = new BufferedReader(fr);
String str =null;
//逐行读取
while((str=br.readLine())!=null){
System.out.println(str);
}

InputStreamReader(字符输出流)

public static void main(String[] args) {
//字节流转字符流
FileInputStream fis=null;
InputStreamReader isr = null;
BufferedReader br =null;
try {
fis = new FileInputStream("D:/IoFile/File/isr.txt");
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String str=null;
while((str=br.readLine())!=null){
sb.append(str+"\r\n");
}
System.out.println(sb.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
if(br!=null){
br.close();
}
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

换行输出


FileWriter fw=null; fw = new FileWriter("D:/IoFile/fw.txt");
// \r\n 换行
fw.write("求知若饥\r\n");
fw.write("噼里啪啦");
System.out.println("写入成功!");

BufferedWriter

换行输出

        BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("D:/IoFile/File/bw.txt"));
bw.write("第一段测试");
//换行
bw.newLine();
bw.write("测试第二段");
System.out.println("写入成功!");
}

FileOutputStream

        try {
//把程序和目标源建立连接
FileOutputStream fos = new FileOutputStream("D:/IoFile/out.txt");
//把字符串转成字节数组
String str = "求知若愚,虚心若饥";
fos.write(str.getBytes());
//flush 把数据完全冲刷到目标源中
fos.flush();
fos.close();
System.out.println("文件写入成功!"); }

BufferedOutputStream

try {
//把程序和目标源建立连接
//Buffer更加安全
//直接传文件名,默认覆盖原有内容
//文件名+true;在原有内容后追加新内容
// BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/IoFile/buffer.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/IoFile/buffer.txt",true));
//把字符串转成字节数组
String str = "求知若愚,虚心若饥";
bos.write(str.getBytes());
//flush 把数据完全冲刷到目标源中
bos.flush();
bos.close();
System.out.println("文件写入成功!"); }

DataOutputStream

        try {
//写入
DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:/IoFile/data.txt"));
dos.writeBoolean(true);
dos.writeInt(110);
dos.writeUTF("求知若饥");
dos.flush();
dos.close();
System.out.println("写入成功!"); }

PrintStream

//构造参数传System,out,就是在控制台打印信息
// PrintStream ps = new PrintStream(System.out);
// ps.print("132546u");
try {
PrintStream ps1=
new PrintStream
(new FileOutputStream("D:/IoFile/print.txt"));
ps1.println("虚心若愚");
ps1.println("求知若饥");
ps1.println("求知若饥");
ps1.println("虚心若愚");
ps1.flush();
ps1.close();
System.out.println("写入成功!");
}

Java——I/O相关练习代码的更多相关文章

  1. java 发送邮件 email相关操作代码测试,生成复杂格式邮件,发送邮件相关操作

    项目源码下载:http://download.csdn.net/detail/liangrui1988/6720047 效果图: 相关代码: test1 package com.mail; impor ...

  2. java文件夹相关操作 演示样例代码

    java文件夹相关操作 演示样例代码 package org.rui.io; import java.io.File; import java.io.FilenameFilter; import ja ...

  3. Java内存模型相关原则详解

    在<Java内存模型(JMM)详解>一文中我们已经讲到了Java内存模型的基本结构以及相关操作和规则.而Java内存模型又是围绕着在并发过程中如何处理原子性.可见性以及有序性这三个特征来构 ...

  4. 推荐Java五大微服务器及其代码示例教程

    来源素文宅博客:http://blog.yoodb.com/yoodb/article/detail/1339 微服务越来越多地用于开发领域,因为开发人员致力于创建更大,更复杂的应用程序,这些应用程序 ...

  5. Java 并发,相关术语

    Java 并发,相关术语: 术语 作用 synchronize 可修饰方法.代码块.类:介绍:https://www.cnblogs.com/zyxiaohuihui/p/9096882.html L ...

  6. paip.java 注解的详细使用代码

    paip.java 注解的详细使用代码 作者Attilax 艾龙,  EMAIL:1466519819@qq.com 来源:attilax的专栏 地址:http://blog.csdn.net/att ...

  7. 在Java中直接调用js代码(转载)

    http://blog.csdn.net/xzyxuanyuan/article/details/8062887 JDK1.6版添加了新的ScriptEngine类,允许用户直接执行js代码. 在Ja ...

  8. 在Java中直接调用js代码

    JDK1.6版添加了新的ScriptEngine类,允许用户直接执行js代码. 在Java中直接调用js代码 不能调用浏览器中定义的js函数,会抛出异常提示ReferenceError: “alert ...

  9. java 覆盖hashCode()深入探讨 代码演示样例

    java 翻盖hashCode()深入探讨 代码演示样例 package org.rui.collection2.hashcode; /** * 覆盖hashcode * 设计HashCode时最重要 ...

随机推荐

  1. 当layui与分页相遇--bootstrap何去何从

    用了一段时间,感觉layui比bootstrap 方便了很多.在js操作上比bootstrap减少了许多的代码量. 今天遇到需要前台分页.当然,不是表格,如果是表格的话.使用yalui table和b ...

  2. 【Termux】使用指南

    直入主题: 1.1 下载安装 Google下载(有条件的用!) F-droid下载(建议使用!) ps:不建议去酷安下载! 1.2 配置 apt update && apt upgra ...

  3. Android——几种数据存储应用浅谈

    (1)android中的数据存储主要有五种方式: 第一种.sharedPreferences存储数据, 适用范围:保存少量的数据,且这些数据的格式非常简单:字符串型.基本类型的值.比如应用程序的各种配 ...

  4. 我与CSDN的第一百天

  5. 使用Python实现的4种快速排序算法

    快速排序算法,总体来说就是选一个基准值,把小于基准值的分一拨,把大于基准值的分到另一拨,然后递归. 有区别的是,分区算法有差异,最直接的是,选个基准值,定义两个列表(小值分区less和大值分区grea ...

  6. 万万没想到,面试中,连 ClassLoader类加载器 也能问出这么多问题…..

    1.类加载过程 类加载时机 「加载」 将类的.class文件中的二进制数据读入到内存中,将其放在运行时数据区的方法区内,然后在内存上创建一个java.lang.Class对象用来封装类在方法区内的数据 ...

  7. yolov5实战之皮卡丘检测

    前言 从接触深度学习开始一直都做的是人脸识别,基本上也一直都在用mxnet. 记得之前在刚接触的时候看到博客中写到,深度学习分三个层次,第一个层次是分类,第二个层次是检测,第三个层次是分割.人脸识别算 ...

  8. 【Flutter】可滚动组件之CustomScrollView

    前言 CustomScrollView是可以使用Sliver来自定义滚动模型(效果)的组件.它可以包含多种滚动模型,举个例子,假设有一个页面,顶部需要一个GridView,底部需要一个ListView ...

  9. Oracle 索引原理分析

    索引是一种允许直接访问数据表中某一数据行的树型结构,为了提高查询效率而引入,是一个独立于表的对象,可以存放在与表不同的表空间中.索引记录中存有索引关键字和指向表中数据的指针(地址).对索引进行的I/O ...

  10. leetcode 470. 用 Rand7() 实现 Rand10() (数学,优化策略)

    题目链接 https://leetcode-cn.com/problems/implement-rand10-using-rand7/ 题意: 给定一个rand7()的生成器,求解如何产生一个rand ...