File类:

 import java.io.File;
import java.io.IOException; public class Demo{
public static void main(String[] args){
//将a.txt封装成file对象。可以将已有的和未出现的文件或者文件夹封装成对象
File f1 = new File("a.txt"); //左边参数是父目录,右边是文件名
File f2 = new File("C:", "demo.txt"); File d = new File("C:\\abc");
File f3 = new File(d, "c.txt"); //因为\\是windows下的分割符,而File.separator是可以跨平台的
ile f4 = new File("C:" + File.separator + "abc" + File.separator + "c.txt");
}
}

File类常见方法:

(1)创建:boolean createNewFile(); 在指定位置创建文件,如果该文件已经存在,则不创建,返回false。和输出流不一样,输出流对象一建立,就会创建文件,而且文件已经存在,会覆盖。

       boolean mkdir();  创建文件夹。

       boolean mkdirs();  创建多级文件夹。

(2)删除:boolean delete();   删除失败返回false。

       boolean deleteOnExit();  在程序退出时删除指定文件。

(3)判断:boolean canExecute(); 测试应用程序是否可以执行此抽象路径名表示的文件。

       boolean exists(); 文件是否存在。

       isFile();

       isDirectory();

         isHidden();

       isAbsolute();  测试此抽象路径名是否为绝对路径名。

       在判断文件对象是否是文件或者目录时,必须要先判断该文件对象封装的内容是否存在,通过exists判断。

(4)获取信息:

       getName();   getPath();   getParent();   getAbsolutePath();  long lastModified(); 文件最后一次被修改的时间    long length();

输出C盘下所有文件和文件夹的名字:

 import java.io.File;
import java.io.IOException; public class Demo{
public static void main(String[] args){
File f = new File("C:\\");
String[] names = f.list();
for(String name : names){
System.out.println(name);
}
}
}

输出G盘中后缀名为.txt的文件名:

 import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException; public class Demo{
public static void main(String[] args) throws IOException{
// File f = new File("G:\\");
// String[] arr = f.list(new FilenameFilter(){
// public boolean accept(File dir, String name){
// return name.endsWith(".txt");
// }
// });
// for(String name : arr){
// System.out.println(name);
// } File f = new File("G:\\");
File[] files = f.listFiles(new FilenameFilter() {
public boolean accept(File f, String name) {
return name.endsWith(".txt");
}
});
for(File file : files){
System.out.println(file.getName());
}
}
}

列出指定目录下文件或文件夹,包含目录中的内容。也就是列出指定目录下所有内容(递归):

 import java.io.File;
import java.io.IOException; public class Demo{
public static void main(String[] args){
File dir = new File("F:\\text");
showDir(dir);
}
public static void showDir(File dir){
System.out.println(dir);
File[] files = dir.listFiles();
for(File f : files){
if(f.isDirectory()){
showDir(f);
}
else{
System.out.println(f);
}
}
}
}

加入层次效果:

 import java.io.File;
import java.io.IOException; public class Demo{
public static void main(String[] args){
File dir = new File("F:\\text");
showDir(dir, 0);
}
public static String getLevel(int level){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < level; i++){
sb.append(" ");
}
return sb.toString();
}
public static void showDir(File dir, int level){
System.out.println(getLevel(level) + dir);
level++;
File[] files = dir.listFiles();
for(File f : files){
if(f.isDirectory()){
showDir(f, level);
}
else{
System.out.println(getLevel(level) + f);
}
}
}
}

删除一个带内容的目录。删除原理:在windows中,删除目录从里往外删除。所以就需要递归:

 import java.io.File;

 public class Demo{
public static void main(String[] args){
File dir = new File("F:\\testdir");
removeDir(dir);
}
public static void removeDir(File dir){
File[] files = dir.listFiles();
for(File file : files){
if(file.isDirectory()){
removeDir(file);
}
else{
System.out.println(file.toString() + ":-file-" + file.delete());
}
}
System.out.println(dir + "::dir::" + dir.delete());
}
}

将一个指定目录下的Java文件的绝对路径,存储到一个文本文件中。建立一个Java列表文件。

 import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; public class Demo{
public static void main(String[] args){
File dir = new File("C:\\Users\\ZTQ\\Desktop\\JavaText");
List<File> list = new ArrayList<File>();
fileToList(dir, list);
File file = new File(dir, "javalist.txt");
writeToFile(list, file.toString());
}
//目录中的.java文件写入到list中
public static void fileToList(File dir, List<File> list){
File[] files = dir.listFiles();
for(File f : files){
if(f.isDirectory()){
fileToList(f, list);
}
else{
list.add(f);
}
}
}
//list写入到文件中
public static void writeToFile(List<File> list, String path){
BufferedWriter bufw = null;
try{
bufw = new BufferedWriter(new FileWriter(path));
for(File f : list){
String p = f.getAbsolutePath();
bufw.write(p);
bufw.newLine();
bufw.flush();
}
}catch(IOException e){
throw new RuntimeException(e.toString());
}finally{
if(bufw != null){
try{
bufw.close();
}catch(IOException e){
throw new RuntimeException(e.toString());
}
}
}
}
}

Properties是hashtable的子类。它具备map集合的特点,而且它里面存储的键值对都是字符串。是集合中与IO技术相结合的集合容器。对象特点:可以用于键值对形式的配置文件。

 import java.util.Properties;
import java.util.Set; public class Demo{
public static void main(String[] args){
setAndGet();
}
public static void setAndGet(){
Properties prop = new Properties();
prop.setProperty("zhangsan", "30");
prop.setProperty("lisi", "40"); String value = prop.getProperty("lisi");
System.out.println(value); prop.setProperty("lisi", "50");
Set<String> names = prop.stringPropertyNames();
for(String s : names){
System.out.println(s + ":" + prop.getProperty(s));
}
}
}

将info.txt中键值数据存到集合中进行操作:

(1)用一个流和info.txt文件关联

(2)读取一行数据,将该行数据用“=”进行切割

(3)“=”左边作为键,右边作为值,存入到Properties集合中即可。

 import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties; public class Demo{
public static void main(String[] args)throws IOException{
method_02();
}
public static void method_01() throws IOException{
BufferedReader bufr = new BufferedReader(new FileReader("F:\\demo.txt"));
String line = null;
Properties prop = new Properties();
while((line = bufr.readLine()) != null){
String[] arr = line.split("=");
prop.setProperty(arr[0], arr[1]);
}
bufr.close();
System.out.println(prop);
}
public static void method_02()throws IOException{
FileInputStream fis = new FileInputStream("F:\\demo.txt");
Properties prop = new Properties();
//将流中的数据加载进集合
prop.load(fis); // prop.setProperty("wangwu", "39"); 只能设置内存中的内容,而文件中的内容不改变
FileOutputStream fos = new FileOutputStream("F:\\demo.txt");
prop.store(fos, "haha"); //第二个参数为注释信息 prop.list(System.out);
fis.close();
fos.close();
} }

记录应用程序运行次数,如果使用次数已到,给出注册提示:

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties; public class Demo{
public static void main(String[] args)throws IOException{
Properties prop = new Properties(); File file = new File("F:\\count.ini");
if(!file.exists())
file.createNewFile(); FileInputStream fis = new FileInputStream(file); prop.load(fis); int count = 0;
String value = prop.getProperty("times"); if(value != null){
count = Integer.parseInt(value);
if(count >= 5){
System.out.println("使用次数已到,请充值!");
return;
}
}
count++; prop.setProperty("times", count + ""); FileOutputStream fos = new FileOutputStream(file);
prop.store(fos, ""); fis.close();
fos.close();
}
}

打印流:该流提供了打印方法,可以将各种数据类型的数据都原样打印。

字节打印流 PrintStream:

  构造函数可以接收的参数类型:

  (1)file对象。File

  (2)字符串路径。String

  (3)字节输出流。OutputStream

字符打印流 PrintWriter:

  构造函数可以接收的参数类型:

  (1)file对象。File

  (2)字符串路径。String

  (3)字节输出流。OutputStream

  (4)字符输出流。Writer

 import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter; public class Demo{
public static void main(String[] args)throws IOException{
BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new FileWriter("F:\\demo.txt"), true); //第二个参数为true,则println,printf或format方法将刷新输出缓冲区 String line = null;
while((line = bufr.readLine()) != null){
if("over".equals(line)) break;
out.println(line.toUpperCase());
}
out.close();
bufr.close();
}
}

合并流SequenceInputStream:

 import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector; public class Demo{
public static void main(String[] args)throws IOException{
Vector<FileInputStream> v = new Vector<FileInputStream>();
v.add(new FileInputStream("F:\\1.txt"));
v.add(new FileInputStream("F:\\2.txt"));
v.add(new FileInputStream("F:\\3.txt")); Enumeration<FileInputStream> en = v.elements();
SequenceInputStream sis = new SequenceInputStream(en);
FileOutputStream fos = new FileOutputStream("F:\\4.txt");
byte[] buf = new byte[1024];
int len = 0;
while((len = sis.read(buf)) != -1){
fos.write(buf, 0, len);
}
fos.close();
sis.close();
}
}

切割文件:

 import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator; public class Demo{
public static void main(String[] args)throws IOException{
splitFile();
merge();
}
public static void splitFile() throws IOException{
FileInputStream fis = new FileInputStream("F:\\pic.jpg");
FileOutputStream fos = null; byte[] buf = new byte[1024];
int len = 0;
int count = 1;
while((len = fis.read(buf)) != -1){
fos = new FileOutputStream("F:\\" + count++ + ".part");
fos.write(buf, 0, len);
fos.close();
}
fis.close();
}
public static void merge()throws IOException{
ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
for(int i = 1; i <= 4; i++){
al.add(new FileInputStream("F:\\" + i + ".part"));
}
final Iterator<FileInputStream> it = al.iterator();
Enumeration<FileInputStream> en = new Enumeration<FileInputStream>(){
public boolean hasMoreElements() {
return it.hasNext();
}
public FileInputStream nextElement() {
return it.next();
}
};
SequenceInputStream sis = new SequenceInputStream(en);
FileOutputStream fos = new FileOutputStream("F:\\merge.jpg");
int len = 0;
byte[] buf = new byte[1024];
while((len = sis.read(buf)) != -1){
fos.write(buf, 0, len);
}
fos.close();
sis.close();
}
}

对象的序列化:

 import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; public class Demo{
public static void main(String[] args)throws Exception{
writeObj();
readObj();
}
public static void readObj()throws Exception{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:\\obj.txt"));
Person p = (Person)ois.readObject();
System.out.println(p);
ois.close();
}
public static void writeObj()throws Exception{
ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream("F:\\obj.txt"));
oos.writeObject(new Person("ztq", 23));
oos.close();
}
}

管道流:

管道输入流应该连接到管道输出流,管道输入流提供要写入管道输出流的所有数据字节。通常,数据由某个线程从PipedInputStream对象读取,并由其他线程将其写入到对应的PipedOutputStream。不建议对这两个对象尝试使用单个线程,因为这样可能死锁线程。

 import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream; class Read implements Runnable{
private PipedInputStream in;
Read(PipedInputStream in){
this.in = in;
}
public void run(){
try{
byte[] buf = new byte[1024];
int len = in.read(buf);
String s = new String(buf, 0, len);
System.out.println(s);
in.close();
}catch(IOException e){
throw new RuntimeException("管道读取流失败!");
}
}
} class Write implements Runnable{
private PipedOutputStream out;
Write(PipedOutputStream out){
this.out = out;
}
public void run(){
try{
out.write("piped!~".getBytes());
out.close();
}catch(IOException e){
throw new RuntimeException("管道输入流失败!");
}
}
}
public class Demo{
public static void main(String[] args)throws Exception{
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
in.connect(out);
new Thread(new Read(in)).start();
new Thread(new Write(out)).start();
} }

RandomAccessFile:

该类不算是IO体系中的子类,直接继承的Object。但它却是IO包中的成员,因为它具备读和写功能,内部封装了一个数组,而且通过指针对数组的元素进行操作,可以通过getFilePointer获取指针位置,同时可以通过seek改变指针的位置。

其实完成读写的原理就是内部封装了字节输入输出流。

通过构造函数可以看出,该类只能操作文件。而且操作文件还有模式mode:如r只读,rw读和写等。如果模式为r,不会创建文件,会读取一个已存在的文件,如果文件不存在,则会出现异常。如果模式为rw,操作的文件不存在,会自动创建,如果存在则不会覆盖。

 import java.io.IOException;
import java.io.RandomAccessFile; public class Demo{
public static void main(String[] args)throws Exception{
writeFile_2();
readFile();
}
public static void readFile() throws IOException{
RandomAccessFile raf = new RandomAccessFile("F:\\ran.txt", "r"); //调整对象中的指针
raf.seek(8); //跳过指定的字节数,只能往后跳
//raf.skipBytes(8); byte[] buf = new byte[4];
raf.read(buf);
String name = new String(buf);
int age = raf.readInt();
System.out.println("name = " + name);
System.out.println("age = " + age);
raf.close();
}
public static void writeFile() throws IOException{
RandomAccessFile raf = new RandomAccessFile("F:\\ran.txt", "rw");
raf.write("李四".getBytes());
raf.writeInt(97);
raf.write("王五".getBytes());
raf.writeInt(99);
raf.close();
}
public static void writeFile_2() throws IOException{
RandomAccessFile raf = new RandomAccessFile("F:\\ran.txt", "rw");
raf.seek(8 * 1);
raf.write("哈哈".getBytes());
raf.close();
}
}

DataStream:

可以用于操作基本数据类型的流对象。

 import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; public class Demo{
public static void main(String[] args)throws Exception{
writeData();
readData();
}
public static void writeData() throws IOException{
DataOutputStream dos = new DataOutputStream(new FileOutputStream("F:\\demo.txt"));
dos.writeInt(123);
dos.writeBoolean(true);
dos.writeDouble(12.34);
dos.close();
}
public static void readData() throws IOException{
DataInputStream dis = new DataInputStream(new FileInputStream("F:\\demo.txt"));
int n1 = dis.readInt();
boolean n2 = dis.readBoolean();
double n3 = dis.readDouble();
System.out.println("n1 = " + n1);
System.out.println("n2 = " + n2);
System.out.println("n3 = " + n3);
dis.close();
}
}

ByteArrayStream:

用于操作字节数组的流对象。

ByteArrayInputStream:在构造的时候,需要接受数据源,而且数据源是一个字节数组。

ByteArrayOutputStream:在构造的时候,不用定义数据目的,因为该对象中已经内部封装了可变长度的字节数组,这就是数据目的地。

因为这两个流对象都操作的数组,并没有使用系统资源,所以不用进行close关闭。

 import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; public class Demo{
public static void main(String[] args){
//数据源
ByteArrayInputStream bis = new ByteArrayInputStream("ABCDEFG".getBytes()); //数据目的
ByteArrayOutputStream bos = new ByteArrayOutputStream(); int by = 0;
while((by = bis.read()) != -1){
bos.write(by);
} System.out.println(bos.size());
System.out.println(bos.toString());
} }

编码:字符串变成字节数组。

解码:字节数组变成字符串。

String-->byte[]   str.getBytes();

byte[]-->String   new String(byte[]);

有五个学生,每个学生有3门课的成绩,从键盘输入以上数据(包括姓名,三门课成绩),输入的格式,如:zhangsan,30,40,60计算出总成绩,并把学生的信息和计算出的总分数按照高低顺序存放在磁盘文件“stud.txt”中:

 import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet; class Student implements Comparable<Student>{
private String name;
private int c1, c2, c3;
private int sum; public Student(String name, int c1, int c2, int c3){
this.name = name;
this.c1 = c1;
this.c2 = c2;
this.c3 = c3;
sum = c1 + c2 + c3;
} public String getName(){
return name;
} public int getSum(){
return sum;
} public int hashCode(){
return name.hashCode() + sum * 78;
} public boolean equals(Object obj){
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配");
Student s = (Student)obj;
return this.name.equals(s.name) && this.sum == s.sum;
} public int compareTo(Student s) {
int num = new Integer(this.sum).compareTo(new Integer(s.sum));
if(num == 0){
return this.name.compareTo(s.name);
}
return num;
} public String toString(){
return "Student[ " + name + ", " + c1 + ", " + c2 + ", " + c3 + " ]";
}
} class StudentInfoTool{
//使用默认比较器的方法
public static Set<Student> getStudents() throws IOException{
return getStudents(null);
}
//使用传入的比较器的方法
public static Set<Student> getStudents(Comparator<Student> cmp) throws IOException{
BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));
String line = null;
Set<Student> stus = null;
if(cmp == null)
stus = new TreeSet<Student>();
else
stus = new TreeSet<Student>(cmp);
while((line = bufr.readLine()) != null){
if("over".equals(line))
break;
String[] arr = line.split(",");
Student stu = new Student(arr[0], Integer.parseInt(arr[1]),
Integer.parseInt(arr[2]),
Integer.parseInt(arr[3]));
stus.add(stu);
}
bufr.close();
return stus;
}
public static void write2File(Set<Student> stus) throws IOException{
BufferedWriter bufw = new BufferedWriter(new FileWriter("F:\\students.txt"));
for(Student stu : stus){
bufw.write(stu.toString());
bufw.write(" " + stu.getSum());
bufw.newLine();
bufw.flush();
}
bufw.close();
}
}
public class Demo{
public static void main(String[] args) throws IOException{
Comparator<Student> cmp = Collections.reverseOrder();
Set<Student> stus = StudentInfoTool.getStudents(cmp);
StudentInfoTool.write2File(stus);
}
}

Java笔记(七)的更多相关文章

  1. 疯狂java笔记(七) - Java集合之Map

    Map是以键值对(key-value)的形式来存储数据的.而且Map不允许key的重复,通过Map存储key-value对时,只需要考虑key的存储就可以,key存储后value就会跟着key(完全可 ...

  2. Java笔记(七)……函数

    函数的定义 定义在类中具有特定功能的一段独立小程序,也称方法. 函数的格式 1: 修饰符 返回值类型 函数名(参数类型 形式参数1,参数类型 形式参数2,) 2: { 3: 执行语句; 4: retu ...

  3. Java IO学习笔记七:多路复用从单线程到多线程

    作者:Grey 原文地址:Java IO学习笔记七:多路复用从单线程到多线程 在前面提到的多路复用的服务端代码中, 我们在处理读数据的同时,也处理了写事件: public void readHandl ...

  4. Elasticsearch笔记七之setting,mapping,分片查询方式

    Elasticsearch笔记七之setting,mapping,分片查询方式 setting 通过setting可以更改es配置可以用来修改副本数和分片数. 1:查看,通过curl或浏览器可以看到副 ...

  5. Typescript 学习笔记七:泛型

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  6. Go语言学习笔记七: 函数

    Go语言学习笔记七: 函数 Go语言有函数还有方法,神奇不.这有点像python了. 函数定义 func function_name( [parameter list] ) [return_types ...

  7. Java笔记 —— 继承

    Java笔记 -- 继承 h2{ color: #4ABCDE; } a{ text-decoration: none!important; } a:hover{ color: red !import ...

  8. Java 笔记 —— java 和 javac

    Java 笔记 -- java 和 javac h2{ color: #4ABCDE; } a{ text-decoration: none !important; } a:hover{ color: ...

  9. 《Java笔记——基础语法》

    Java笔记--基础语法       一.字符串的拼接: 例如: System.out.println(""+"");     二.换行语句: 例如: Syst ...

  10. Effective Java笔记一 创建和销毁对象

    Effective Java笔记一 创建和销毁对象 第1条 考虑用静态工厂方法代替构造器 第2条 遇到多个构造器参数时要考虑用构建器 第3条 用私有构造器或者枚举类型强化Singleton属性 第4条 ...

随机推荐

  1. 利用VideoView播放视频

    package com.qianhua.ui; 002   003 import android.app.Activity; 004 import android.content.Intent; 00 ...

  2. Odoo POS

    Jeffery Q:913547235     Odoo 8 只支持 ean13条码 Barcode scanner相当于键盘,30ms 条码枪输出类型,QWERTY     pos配置       ...

  3. python去除停用词(结巴分词下)

    python 去除停用词  结巴分词 import jieba #stopwords = {}.fromkeys([ line.rstrip() for line in open('stopword. ...

  4. create a backdoor deb package

    以下介绍怎样制作包括后门的deb安装包.以tree为例进行说明.利用apt-get下载安装包.--download-only表示仅仅下载不做其它处理. root@deb:~#apt-get downl ...

  5. C# 知识点随手学习网站推荐

    http://www.studyofnet.com/news/list-8881.2-1-1.html

  6. grep man 有删减 百科

    NAME grep, egrep, fgrep, rgrep - print lines matching a pattern SYNOPSIS grep [OPTIONS] PATTERN [FIL ...

  7. Citrix_XenServer-6.1安装过程详解(转)

    本次为使用VirtualBox虚拟机过安装测试机过程,我们在使用Vm(无论是Vbox还是VMware等)我们的CPU都必须可支持Intel-V或AMD-V,并且在VM软件设置和BIOS设置开启虚拟化支 ...

  8. Ubuntu16.04下自定义命令

    每次启动pycharm的时候需要敲一段很长的文本,真的是感觉好麻烦啊,如果能直接敲命令启动就好了,既装B又实用的 那么到底应该怎么做呢?其实挺简单的 在文件/root/.bashrc 中添加下边的几行 ...

  9. transient、volatile关键字

    transient是在对象序列化的时候,不参与序列化的字段. 如LinkedList实现了Serializable,其中有变量transient int size = 0; 在Serializable ...

  10. oracle sqlplus 常用操作

    命令 含义 / 运行 SQL 缓冲区 ? [关键词] 对关键词提供 SQL 帮助 @[@] [文件名] [参数列表] 通过指定的参数,运行指定的命令文件 ACC[EPT] 变量 [DEF[AULT] ...