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. Linux性能优化:CPU性能分析工具--vmstat

    Blog:博客园 个人 目录 参数说明 输出信息说明 procs memory swap io system cpu 示例 vmstat是Virtual Meomory Statistics(虚拟内存 ...

  2. Java源码系列4——HashMap扩容时究竟对链表和红黑树做了什么?

    我们知道 HashMap 的底层是由数组,链表,红黑树组成的,在 HashMap 做扩容操作时,除了把数组容量扩大为原来的两倍外,还会对所有元素重新计算 hash 值,因为长度扩大以后,hash值也随 ...

  3. Turtlebot3新手教程:仿真

    本文章针对如何利用turtlebot3实现仿真功能进行讲解 测试环境:Ubuntu 16.04 和 ROS Kinetic Kame. 注意:TurtleBot3 Simulation 依赖 turt ...

  4. 第13章节 BJROBOT 雷达跟随【ROS全开源阿克曼转向智能网联无人驾驶车】

    雷达跟随说明:注意深度摄像头的 USB 延长线,可能会对雷达扫描造成影响, 所以在雷达跟随前,把深度摄像头的 USB 延长线取下.另外雷达跟随范围大概是前方 50cm 和 120°内扫描到的物体都可以 ...

  5. C#中的格式

    格式模式 说明 : d 月中的某一天.一位数的日期没有前导零. dd 月中的某一天.一位数的日期有一个前导零. ddd 周中某天的缩写名称,在 AbbreviatedDayNames 中定义. ddd ...

  6. 修改postman工具的代码生成工具让它锦上添花

    @font-face { font-family: octicons-link; src: url("data:font/woff;charset=utf-8;base64,d09GRgAB ...

  7. day121:MoFang:植物的状态改动(幼苗→成长期)&植物的浇水功能

    目录 1.当果树种植以后在celery的异步任务中调整浇水的状态 2.客户端通过倒计时判断时间,显示浇水道具 3.客户端判断当前种植物状态控制图标的显示和隐藏 4.当用户单击浇水图标, 则根据当前果树 ...

  8. springboot异常处理之404

    ps: 推荐一下本人的通用后台管理项目crowd-admin 以及newbee-mall增强版,喜欢的话给个star就好 源码分析 在springboot中默认有一个异常处理器接口ErrorConto ...

  9. 跨站脚本漏洞(XSS)基础

    什么是跨站脚本攻击XSS 跨站脚本(cross site script),为了避免与样式css混淆所以简称为XSS,是一种经常出现在web应用中的计算机安全漏洞,也是web中最主流的攻击方式. 什么是 ...

  10. Unsafe Fileupload - Pikachu

    概述: 文件上传功能在web应用系统很常见,比如很多网站注册的时候需要上传头像.上传附件等等.当用户点击上传按钮后,后台会对上传的文件进行判断 比如是否是指定的类型.后缀名.大小等等,然后将其按照设计 ...