java 文件处理

16 篇文章 0 订阅

1. 文件对象

import java.io.File;

File f1 = new File('./hello.txt');

f1.getAbsolutePath(); //绝对路径
File f2 = new File("E:/");
File f3 = new File(f2, "world.txt"); //f2作为父目录创建world.txt对象

f1.exists();
f1.isDirectory();
f1.isFile();
f1.length();

long t1 = f1.lastModified();
Date d1 = new Date(t1);
f1.setLastModified(0);

f1.renameTo(f3); //hello.txt重命名为world.txt

f2.list(); //当前目录下所有文件,数组形式

f1.getParent(); //f1所在文件夹, 字符串形式
f1.getParentFile();  //所在文件夹, 文件形式

f2.mkdir(); //父文件夹不存在就创建
f2.mkdirs();

f2.createNewFile(); //创建空文件
f2.getParentFile().mkdirs(); //创建父目录

f2.listRoots(); //列出所有盘符, c: d:
f.delete(); //删除文件
f.deleteOnExit(); //JVM结束时删除,用于临时文件

2. 文件流

一系列的数据,Stream, 不同介质之间数据交互

字节输入流:InputStream类为抽象类。 FileInputStream是其子类.

字节输出流: OutputStream类为抽象类,FileOutputStream是其子类。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class StreamTest {
    public static void main(String[] args){
        try{
            File f = new File("./hello.txt");
            FileInputStream fis = new FileInputStream(f);
            byte[] fbytes = new byte[ (int) f.length() ]; //字节数组
            fis.read(fbytes); //以字节流形式读取
            for (byte fb: fbytes){
                sout(fb); //输出
            }
            fis.close(); //使用完流需关闭
            
            File fw = new File("./world.txt");
            FileOutputStream fos = new FileOutputStream(fw); //基于文件的输出流
            fos.write(fbytes); //数据写入到输出流
            fos.close();
        }catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

            

3. 关闭流

1)在try中关闭,异常时可能不能关闭;

2) 在finally中关闭,定义在try前

3) try-with-resources定义在try中

//定义在try之前
FileInputStream fis = null;
try{
    ...;
}catch (Exception e) {
}finally{
    if (null != fis)
        try{
            fis.close();
        }catch (IOException e){
        }
    }
}

//定义在try()里,try-with-resources, try..catch..finally结束时自动关闭
try(FileInputStream fis = new FileInputStream(f)){
...
}catch(Exception ex){
}

4. 字符流

java.io.File;FileReader;FileWriter;IOException

Reader: 输入流

Writer: 输出流

FileReader fr = new FileReader(f);

char[] a = new char[ (int) f.length()];

fr.read(a);

for (char c : a){}

String s = "abcdefg"

char[] cs = data.toCharArray();

Filewriter fw = new FileWriter(f);

fr.write(c);

 

5. 编码

数字和西欧字母: ISO-8859-1(含ASCII), ASCII, 1个字节

中文: GBK, GB2312, BIG5(GB2312简体, BIG5繁体, GBK含简体、繁体、日文)

万国码(统一码): UNICODE(含所有文字),4个字节

UTF-8: UNICODE的子编码,数字、字母为1字节;汉字为3字节。

FileReader()使用的是Charset.defaultCharset()的返回值,中文为GBK,英文为ISO-8859-1

System.out.printf(Charset.defaultCharset());

InputStreamReader isr = new InputStreamReader(new FileInputStream(f), Charset.forName("UTF-8"));

 

6. 缓存流

BufferedReader

PrintWriter

建立在存在的流基础上。

FileReader fr = new FileReader(f);

BufferedReader br = new BufferedReader(fr);

String line = br.readLine();

FileWriter fw = new FileWriter(f);

PrinterWriter pw = new PrinterWriter(fw);

pw.println("aaa");

pw.flush(); //立即写入文件,无需等缓存区满

 

7. 数据流

DataInputStream

DataOutputStream

writeUTF(), readUTF()可进行数据的格式化顺序读写

FileInputStream fis = new FileInputStream(f);

DataInputStream dis = new DataInputStream(fis);

FileOutputStream fos = new FileOutputStream(f);

DataOutputStream dos = new DataOutputStream(fos);

int i = dis.readInt();

boolean b = dis.readBoolean();

String str = dis.readUTF();

dos.writeInt(i);

dos.writeBoolean(b);

dos.writeUTF("hello world");

 

8. 对象流

把对象以流的形式传输(序列化)给其他介质;其对应的类必须实现Serializable接口。

ObjectOutputStream oos;

ObjectInputStream ois;

Man man = new Man();

oos.writeObject(man);

Man m = (Man) ois.readObject()

import java.io.Serializable;
public class Man implements Serializable{
    //类的版本,如果有变化,需修改版本号
    private static final long serialVersionUID = 1L;
}

 

9. 控制台输入输出

System.out/in

System.in.read读取数据

InputStream is = System.in;

while (true) {

    int i = is.read();

    sout(i);

}

Scanner逐行读取

Scanner s = new Scanner(System.in);

while (true){

    String line = s.nextLine();// nextInt()

    sout(line);

}

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值