天天看點

Java應用程式設計_I/O程式設計(File檔案操作 | 位元組字元流 | I/O操作深入 | 輸入與輸出支援 | 對象序列化)一,File檔案操作二,位元組流與字元流三,I/O操作深入四,輸入與輸出支援五,對象序列化

總覽【Java SE】

Java應用程式設計_I/O程式設計(File檔案操作 | 位元組字元流 | I/O操作深入 | 輸入與輸出支援 | 對象序列化)一,File檔案操作二,位元組流與字元流三,I/O操作深入四,輸入與輸出支援五,對象序列化

本文目錄

  • 一,File檔案操作
    • demo_檔案清單顯示
    • demo_檔案批量更名
    • demo_File檔案基本操作
  • 二,位元組流與字元流
    • demo_OutputStream類
    • demo_InputStream類
    • demo_Writer類
    • demo_Reader類
    • demo_轉換流
    • demo_檔案拷貝
  • 三,I/O操作深入
    • demo_記憶體操作流
    • demo_管道流
    • demo_RandomAccessFile_Read
    • demo_RandomAccessFile_Write
  • 四,輸入與輸出支援
    • demo_列印流
    • demo_System的IO
    • demo_BufferedReader類
    • demo_Scanner類
  • 五,對象序列化
    • demo_對象序列化

一,File檔案操作

Java應用程式設計_I/O程式設計(File檔案操作 | 位元組字元流 | I/O操作深入 | 輸入與輸出支援 | 對象序列化)一,File檔案操作二,位元組流與字元流三,I/O操作深入四,輸入與輸出支援五,對象序列化

demo_檔案清單顯示

package cn.io.demo;
import java.io.File;
public class 案例_檔案清單顯示 {
	public static void main(String[] args) {
		File file=new File("E:"+File.separator);
		listDir(file);
	}
	public static void listDir(File file){
		if(file.isDirectory()){
			File result[]=file.listFiles();
			if(result!=null){
				for (int i = 0; i < result.length; i++) {
					listDir(result[i]);	//遞歸将是目錄的檔案路徑遞歸到檔案然後輸出檔案的路徑			
				}
			}
		}
		System.out.println(file);
	}
}

           

demo_檔案批量更名

package cn.io.demo;
import java.io.File;
public class 案例_檔案批量更名 {
	public static void main(String[] args) {
		File file=new File("F:"+File.separator);
		renameDir(file);
	}
	public static void renameDir(File file){
		if(file.isDirectory()){
			File result[]=file.listFiles();
			if(result!=null){
				for (int i = 0; i < result.length; i++) {
					renameDir(result[i]);
				}
			}
		}else{
			if(file.isFile()){//排除空檔案夾的幹擾
				String fileName=null;
				if(file.getName().endsWith(".txts")){
					//public int lastIndexOf(String str)從尾查找指定字元串的位置:找不到傳回-1,找到了傳回對應字元數組下标
					fileName=file.getName().substring(0, file.getName().lastIndexOf("."))+".txt";
					File newFile=new File(file.getParentFile(),fileName);
					file.renameTo(newFile);
				}
			}
		}
	}
}
           

注意不要将代碼中要修改的檔案字尾名修改成重要的字尾名,以防止檔案被破壞。該程式将F盤中的所有字尾名為“.txts”的修改為“.txt”。

demo_File檔案基本操作

package cn.io.demo;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
class MathUtil{
	private MathUtil(){}
	public static double round(double data,int scale){
		return Math.round(data*Math.pow(10, scale))/Math.pow(10, scale);
	}
}
public class File檔案基本操作  {
	public static void main(String[] args)throws Exception {
		File file = new File("F:"+File.separator+"demo.txt");
		if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}
		if(file.exists()){
			file.delete();
		}else{
			file.createNewFile();
		}
		
		File fileB=new File("C:"+File.separator+"Finish.log");
		System.out.println("存在:"+fileB.exists());
		System.out.println("讀取:"+fileB.canRead());
		System.out.println("寫入:"+fileB.canWrite());
		System.out.println("執行:"+fileB.canExecute());
		System.out.println("大小:"+MathUtil.round(fileB.length(), 2)+"KB");
		System.out.println("時間:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format( new Date(fileB.lastModified())));
		System.out.println("目錄:"+fileB.isDirectory());
		System.out.println("檔案:"+fileB.isFile());
		
		File fileC=new File("E:"+File.separator);
		if(fileC.isDirectory()){
			File result[]=fileC.listFiles();
			for (int i = 0; i < result.length; i++) {
				System.out.println(result[i]);
			}
		}
	}
}
           

運作結果

存在:true
讀取:true
寫入:true
執行:true
大小:9.0KB
時間:2019-01-11 15:56:19
目錄:false
檔案:true
E:\$RECYCLE.BIN
E:\Adobe
E:\demo - 快捷方式.lnk
E:\demo.txt
E:\System Volume Information
E:\前端
E:\後端

Process finished with exit code 0
           

二,位元組流與字元流

Java應用程式設計_I/O程式設計(File檔案操作 | 位元組字元流 | I/O操作深入 | 輸入與輸出支援 | 對象序列化)一,File檔案操作二,位元組流與字元流三,I/O操作深入四,輸入與輸出支援五,對象序列化

demo_OutputStream類

package cn.io.demo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class OutputStream類 {
	public static void main(String[] args)throws Exception {
		File file=new File("E:"+File.separator+"demo.txt");
		if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}
		try (OutputStream output=new FileOutputStream(file);){
			String str="hello\r\nhello";
			output.write(str.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		} 		
	}
}

           

demo_InputStream類

package cn.io.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class InputStream類 {

	public static void main(String[] args) throws Exception{
		File file=new File("E:"+File.separator+"demo.txt");
		if(file.exists()){
			InputStream input=new FileInputStream(file);
			byte data[]=new byte[1024];
			int len=input.read(data);
			System.out.println("["+new String(data,0,len)+"]");
			input.close();
		}
	}

}

           

demo_Writer類

package cn.io.demo;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
public class Writer類 {

	public static void main(String[] args)throws Exception {
		File file=new File("E:"+File.separator+"demo.txt");
		if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}
		Writer out=new FileWriter(file);
		out.write("hello world");
		out.append("!");
		out.close();
		
	}

}

           

demo_Reader類

package cn.io.demo;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;

public class Reader類 {

	public static void main(String[] args) throws Exception{
		File file=new File("E:"+File.separator+"demo.txt");
		if(file.exists()){
			Reader read=new FileReader(file);
			char data[]=new char[1024];
			read.skip(2);
			int len=read.read(data);
			System.out.println(new String(data,0,len));
		}
	}

}

           

demo_轉換流

package cn.io.demo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class 轉換流 {

	public static void main(String[] args) throws Exception{
		File file =new File("E:"+File.separator+"demo.txt");
		if(file.exists()){
			OutputStream output=new FileOutputStream(file);
			Writer out=new OutputStreamWriter(output);
			out.write("hello!!");
			out.close();
			output.close();
		}
	}

}

           

demo_檔案拷貝

package cn.io.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

class FileUtil{
	private File srcFile;//源檔案
	private File desFile;//目标檔案
	public FileUtil(File srcFile, File desFile) {
		this.srcFile = srcFile;
		this.desFile = desFile;
	}
	public FileUtil(String srcFile, String desFile) {
		this(new File(srcFile),new File(desFile));//構造調用
	}
	
	public boolean copy() throws Exception{//檔案複制前的基本判斷
		if(!this.srcFile.exists()){
			System.out.println("複制源檔案不存在!");
			return false;
		}
		try{
			this.copyImple(this.srcFile);
			return true;
		}catch(Exception e){
			return false;
		}
	}
	private void copyImple(File file)throws Exception{
		if(file.isDirectory()){
			File result[]=file.listFiles();
			for (int i = 0; i < result.length; i++) {
				copyImple(result[i]);
			}
		}else{
			if(file.isFile()){
				String newFilePath=file.getPath().replace(this.srcFile.getPath()+File.separator, "");
				File newFile = new File(this.desFile,newFilePath);
				this.copyFileImple(file,newFile);
			}
		}
	}
	private void copyFileImple(File srcFileImp,File desFileImp)throws Exception{
		if(!this.desFile.exists()){
			this.desFile.mkdirs();
		}
		byte data[]=new byte[1024];
		InputStream input=null;
		OutputStream output=null;
		
		try{
			input=new FileInputStream(srcFileImp);
			output=new FileOutputStream(desFileImp);
			int len=0;
			while((len = input.read(data))!=-1){
				output.write(data, 0, len);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(input!=null){
				input.close();
			}
			if(output!=null){
				output.close();
			}
		}
	}
	
	
}
public class 案例_檔案拷貝 {
	public static void main(String[] args) throws Exception{
		if(args.length!=2){
			System.out.println("指令參數設定錯誤");
			System.exit(1);
		}
		long start=System.currentTimeMillis();
		FileUtil fu=new FileUtil(args[0],args[1]);
		System.out.println(fu.copy()?"檔案複制成功":"檔案複制失敗");
		long end=System.currentTimeMillis();
		System.out.println("複制花費時間為"+(end-start));
	}
}

           

三,I/O操作深入

Java應用程式設計_I/O程式設計(File檔案操作 | 位元組字元流 | I/O操作深入 | 輸入與輸出支援 | 對象序列化)一,File檔案操作二,位元組流與字元流三,I/O操作深入四,輸入與輸出支援五,對象序列化

【擴充】RandomAccessFile簡介與使用

demo_記憶體操作流

package cn.io.demo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class 記憶體操作流 {

	public static void main(String[] args)throws Exception {
		String str="hello";
		InputStream input=new ByteArrayInputStream(str.getBytes());
		ByteArrayOutputStream output=new ByteArrayOutputStream();//不向上轉型,要使用ByteArrayOutput的toByteArray方法
		int data=0;
		while((data=input.read())!=-1){
			output.write(Character.toUpperCase(data));//将輸入流的内容儲存至輸出流
		}
		byte result[]=output.toByteArray();
		System.out.println(new String(result));
		input.close();
		output.close();
	}

}

           

demo_管道流

package cn.io.demo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class 管道流 {
	public static void main(String[] args)throws Exception {
		SendThread send=new SendThread();
		ReceiveThread receive=new ReceiveThread();
		send.getOutput().connect(receive.getInput());
		new Thread(send,"發送端").start();
		new Thread(receive,"接收端").start();
		
	}
}

class SendThread implements Runnable{
	private PipedOutputStream output;
	public SendThread(){
		this.output=new PipedOutputStream();
	}
	public PipedOutputStream getOutput(){
		return this.output;
	}
	@Override
	public void run() {
		try {
			this.output.write((Thread.currentThread().getName()+"發送資訊:hello").getBytes());
			this.output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
class ReceiveThread implements Runnable{
	private PipedInputStream input;
	public ReceiveThread(){
		this.input=new PipedInputStream();
	}
	public PipedInputStream getInput(){
		return this.input;
	}
	@Override
	public void run() {
		byte data[]=new byte[1024];
		int len=0;
		ByteArrayOutputStream bos=new ByteArrayOutputStream();
		try {
			while((len=input.read(data))!=-1){
				bos.write(data,0,len);
			}
			System.out.println(new String(bos.toByteArray()));
			this.input.close();
			bos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}

           

demo_RandomAccessFile_Read

package cn.io.demo;
import java.io.File;
import java.io.RandomAccessFile;
public class RandomAccessFile_Read {
	public static void main(String[] args) throws Exception{
		File file=new File("E:"+File.separator+"demo.txt");
		RandomAccessFile raf=new RandomAccessFile(file,"rw");
		{//讀取王五 跳過24位
			raf.skipBytes(24);
			byte[] data=new byte[8];
			int len=raf.read(data);
			System.out.println("姓名:"+new String(data,0,len).trim()+"\t年齡:"+raf.readInt());
		}
		{//讀取李四 回跳12位
			raf.seek(12);;
			byte[] data=new byte[8];
			int len=raf.read(data);
			System.out.println("姓名:"+new String(data,0,len).trim()+"\t年齡:"+raf.readInt());
		}
		{//讀取張三 跳回開始點
			raf.seek(0);;
			byte[] data=new byte[8];
			int len=raf.read(data);
			System.out.println("姓名:"+new String(data,0,len).trim()+"\t年齡:"+raf.readInt());
		}
		raf.close();
	}

}

           

demo_RandomAccessFile_Write

package cn.io.demo;
import java.io.File;
import java.io.RandomAccessFile;
class Writer_RA {
	public static void Run(RandomAccessFile raf,String names[],int ages[])throws Exception{
		for(int i=0;i<names.length;i++){
			raf.write(names[i].getBytes());
			raf.writeInt(ages[i]);
		}
		raf.close();
	}
}
public class RandomAccessFile_Writer {
	public static void main(String[] args) throws Exception{
		RandomAccessFile raf=new RandomAccessFile(new File("E:"+File.separator+"demo.txt"),"rw");
		Writer_RA.Run(raf, new String[]{"zhangsan","lisi    ","wangwu  "}, new int[]{10,20,30});
	}
}

           

四,輸入與輸出支援

Java應用程式設計_I/O程式設計(File檔案操作 | 位元組字元流 | I/O操作深入 | 輸入與輸出支援 | 對象序列化)一,File檔案操作二,位元組流與字元流三,I/O操作深入四,輸入與輸出支援五,對象序列化

demo_列印流

package cn.io.demo;
import java.io.File;
import java.io.PrintWriter;
public class 列印流 {
	public static void main(String[] args) throws Exception{
		File file=new File("E:"+File.separator+"demo.txt");
		PrintWriter pri=new PrintWriter(file);
		int age=18;
		pri.print("姓名:");
		pri.println("張三");
		pri.printf("年齡:%d\r\n", age);
		pri.close();
	}
}

           

demo_System的IO

package cn.io.demo;

import java.io.InputStream;

public class System的IO {

	public static void main(String[] args) throws Exception{
		InputStream input=System.in;
		System.out.print("請輸入内容:");
		byte [] data=new byte[1024];
		int len=input.read(data);
		System.out.println("輸入的内容為:"+new String(data,0,len));
		try{
			Integer.parseInt("a");
		}catch(Exception e){
			System.out.println(e);
			System.err.print(e);
		}
	}
}

           

運作結果

請輸入内容:1
輸入的内容為:1

java.lang.NumberFormatException: For input string: "a"
java.lang.NumberFormatException: For input string: "a"(此行紅色)
Process finished with exit code 0
           

demo_BufferedReader類

package cn.io.demo;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class BufferedReader類 {

	public static void main(String[] args) throws Exception{
		BufferedReader buff=new BufferedReader(new InputStreamReader(System.in));
		System.out.println("請輸入你的年齡:");
		String age=buff.readLine();
		if(age.matches("\\d{1,3}")){
			int ages=Integer.parseInt(age);
			System.out.println("你的年齡為"+ages+"歲");
		}else{
			System.out.println("你絕對是來搗亂的!");
		}
	}

}

           

demo_Scanner類

package cn.io.demo;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Scanner;

public class Scanner類 {
	public static void main(String[] args)throws Exception {
		Scanner scan=new Scanner(System.in);
		System.out.println("請輸入你的生日:");
		if(scan.hasNext("\\d{4}-\\d{2}-\\d{2}")){
			String str=scan.next("\\d{4}-\\d{2}-\\d{2}");
			System.out.println("生日為:"+new SimpleDateFormat("yyyy-MM-dd").parse(str));
		}
		scan.close();
		
		Scanner scann=new Scanner(new File("E:"+File.separator+"demo.txt"));
		scann.useDelimiter("\n");
		while(scann.hasNext()){
			System.out.println(scann.next());
		}
		scann.close();
	}

}

           

五,對象序列化

Java應用程式設計_I/O程式設計(File檔案操作 | 位元組字元流 | I/O操作深入 | 輸入與輸出支援 | 對象序列化)一,File檔案操作二,位元組流與字元流三,I/O操作深入四,輸入與輸出支援五,對象序列化

demo_對象序列化

package cn.io.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

@SuppressWarnings(value = { "" })
class Person implements Serializable{
	private String name;
	private int age;
	private transient int mark;
	public Person(String name,int age,int mark){
		this.name=name;
		this.age=age;
		this.mark=mark;
	}
	@Override
	public String toString(){
		return "姓名:"+this.name+",年齡:"+this.age+",不需要序列化的值:"+this.mark;
	}
}
public class 對象序列化 {
	private static final File SAVE_FILE=new File("E:"+File.separator+"demo.txt");
	public static void main(String[] args) throws Exception {
		saveObject(new Person("張三",18,1));
		System.out.println(loadObject());
	}
	public static void saveObject(Object obj)throws Exception{
		ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(SAVE_FILE));
		oos.writeObject(obj);
		oos.close();
	} 
	public static Object loadObject()throws Exception{
		ObjectInputStream ois=new ObjectInputStream(new FileInputStream(SAVE_FILE));
		Object obj=ois.readObject();
		ois.close();
		return obj;
	}

}

           

本文完,歡迎通路或關注我的【Java SE】專欄。

Java應用程式設計_I/O程式設計(File檔案操作 | 位元組字元流 | I/O操作深入 | 輸入與輸出支援 | 對象序列化)一,File檔案操作二,位元組流與字元流三,I/O操作深入四,輸入與輸出支援五,對象序列化