1. 程式人生 > >Java輸入輸出(IO、檔案操作、大量例項)

Java輸入輸出(IO、檔案操作、大量例項)

java 檔案操作基礎實驗大集合

目錄:

實驗50:FileInputStream類的應用

實驗51:FileOutputStream類應用

實驗52:FileReader類的應用

實驗53:FileWriter類的應用

實驗54:檔案操作 (模版程式)

    (1) 學習File類的使用:新建資料夾程式

    (2) 學習在程式中新建檔案:寫入檔案程式

    (3) 學習在程式中向檔案寫入內容:讀取檔案程式

    (4) 學習在程式中讀取檔案內容:獲取檔案資訊程式

    (5) 學習在程式中檢視目錄內容:檢視目錄內容程式

    (6) 學習在程式中刪除檔案:刪除檔案程式

實驗55:讀寫基本型別資料

實驗56:物件的寫入與讀取

實驗57:對檔案的隨機訪問

實驗50:FileInputStream類的應用

編寫一個Java程式,在main()中生成FileInputStream的一個例項,使它能開啟檔案myfile.txt ,並能夠把檔案的內容顯示在螢幕上

import java.io.*;
public class App_50 {
	public static void main(String[] args)throws IOException{
			int i;
			FileInputStream fin; // 注意:該類不能處理中文編碼
			fin = new FileInputStream("myfile.txt"); // 檔名
			do{
				i = fin.read();
				if( i != -1){
					System.out.print((char)i);	
				}
			}while(i != -1); // 讀到檔案的末尾返回值為-1
			fin.close();
	}	
}

實驗51:FileOutputStream類應用

編寫一個java程式,把檔案myfile.txt中的內容複製到檔案yourfile.txt檔案中

import java.io.*;
public class App_51{
	public static void main(String[] args)throws IOException{
		int i;
		FileInputStream fin;
		FileOutputStream fout;
		fin = new FileInputStream("myfile.txt");    // 建立一個FileInputStream物件,從myfile.txt中讀取資訊
		fout = new FileOutputStream("yourname.txt");
		do{
			i = fin.read();       // 讀入一個位元組的二進位制資料
			if(i != -1){          // 將i的地位位元組寫入到輸出流
				fout.write(i);
			}
		}while(i != -1);              // 若輸入流當前位置沒有資料返回-1
		fin.close();
		fout.close();
		System.out.print("已經複製");
	}
} 

實驗52:FileReader類的應用

編寫一個java程式,讀出檔案myfile.txt的內容並把它們顯示到螢幕上

import java.io.*;
public class App_52{
	public static void main(String[] args)throws IOException{
		char[] c = new char[500]; // 設定一個足夠大的陣列
		FileReader fr = new FileReader("myfile.txt");
		int num = fr.read(c); // 讀取檔案裡的內容到數組裡,並返回讀取的長度
		String str = new String(c, 0, num);
		System.out.println("讀取的字元個數為: " + num + ",其內容如下:");
		System.out.println(str);
	}	
}

實驗53:FileWriter類的應用

編寫一個java程式,將字串寫入到檔案中

import java.io.*;
public class App_53{
	public static void main(String[] args) throws IOException{
		FileWriter fw = new FileWriter("test.txt"); // 可以自動建立
		String str1 = "廣大的程式設計愛好者,你好\r\n";
		String str2 = "歡迎使用java";
		fw.write(str1);
		fw.write(str2);
		fw.close();
		System.out.println("已經將檔案寫入到檔案test.txt中");
	}
}

實驗54:檔案操作 (模版程式)

 (1) 學習File類的使用:新建資料夾程式,帶參執行

import java.io.*;
public class File1{
	public static void main(String[] args) throws IOException { 
		// 這裡需要帶參執行程式,  引數為需要建立的一個或多個檔名
		if(args.length == 0){
			System.out.println("沒有需要建立的檔案");
			System.exit(1);
		}	
		for(int i=0; i<args.length; i++)
			new File(args[i]).createNewFile();	
	}	
}

 (2) 學習在程式中新建檔案:寫入檔案程式

import java.io.*;
public class File2{
	public static void main(String[] args) throws IOException {
		BufferedWriter out = new BufferedWriter(new FileWriter("a.txt")); // 建立快取區字元輸出流,需要傳入Write物件
		out.write("廣東金融學院");
		out.newLine();
		out.write("i love java i use java");
		out.flush();
		out.close();
	}	
}

(3) 學習在程式中向檔案寫入內容:讀取檔案程式

import java.io.*;

public class File3{
	public static void main(String[] args)throws IOException{
		String thisLine;
		BufferedReader in = new BufferedReader(new FileReader("a.txt")); // 建立快取區字元輸入流,需要傳如Reader物件
		while((thisLine = in.readLine()) != null)    // 每次讀取一行,直到檔案結束
			System.out.println(thisLine);
		in.close();
	}
}

(4) 學習在程式中讀取檔案內容:獲取檔案資訊程式

 import java.io.*;
import java.util.*;
public class File4{
	public static void status(String fileName) throws IOException{
		System.out.println("------"+fileName+"------");
		File f = new File(fileName);   // 建立 File 類物件
		if(!f.exists()){               // 測試檔案是否存在
			System.out.println("檔案沒收找到"+"\n");
			return;
		}
		System.out.println("檔案全名為:"+f.getCanonicalPath());
		String p = f.getParent();
		if(p!=null){
			System.out.println("Parent directory: "+p); // 顯示檔案的父目錄
		}
		if(f.canRead()){
			System.out.println("File is readable.");    // 測試檔案是否可讀
		}
		if(f.canWrite()){                                   // 測試檔案是否可寫
			System.out.println("File is writable.");
		}
		Date d = new Date();
		d.setTime(f.lastModified());
		System.out.println("Last modifiled : " + d);
		if(f.isFile()){
			System.out.println("檔案大小是: "+f.length()+"bytes");		
		}else if(f.isDirectory()){
			System.out.println("它是目錄");
		}else{
			System.out.println("既不是檔案也不是目錄");	
		}
		System.out.println();
	}
	public static void main(String[] args){
		if(args.length == 0){
			System.out.println("缺少檔名");
			System.exit(1);
		}
		for(int i=0; i<args.length; i++){
			try{status(args[i]);}
			catch(Exception e){ System.out.println(e); }	
		}
	}
}

(5) 學習在程式中檢視目錄內容:檢視目錄內容程式

import java.io.*;
public class File5{
	public static void main(String[] args){
		String[] dir = new java.io.File("C:\\.").list(); // 檢視C盤目錄內容,檢視當前目錄直接用"."
		java.util.Arrays.sort(dir);
		for(int i=0; i<dir.length; i++){
			System.out.println(dir[i]);
		}
		File[] drives = File.listRoots(); // 檢視系統驅動器列表
		for(int i=0; i<drives.length; i++){
			System.out.println(drives[i]);
		}
	}
}

(6) 學習在程式中刪除檔案:刪除檔案程式

import java.io.*;
public class File6{
	public static void main(String[] args){
		File target = new File("a.txt"); // 刪除當前目錄下的 a.txt 檔案
		if(!target.exists())
			System.out.println("檔案不存在");
		else{
			if(target.delete()){
				System.out.println("檔案被刪除");
			}else{
				System.out.println("檔案不能刪除");
			}
		}
	}
}

實驗55:讀寫基本型別資料

編寫一個java程式,在當前資料夾下新建一個檔案baseDate.txt,往該檔案中寫入一些基本型別的資料,再從該檔案中讀取這些資料並顯示.

import java.io.*;
public class BaseDate {
	public static void main(String[] args) {
		FileOutputStream fout;
		DataOutputStream dout;
		FileInputStream fin;
		DataInputStream din;
		try {
			fout = new FileOutputStream("d:\\temp"); // 為了方便檢視,建立在了d盤跟目錄下
			dout = new DataOutputStream(fout);
			dout.writeInt(10);                       // 將int型資料寫入檔案中
			dout.writeLong(1234567894);              // 將Long型別資料寫入
			dout.writeFloat(3.1415926f);             // Float
			dout.writeDouble(5659595.4484);          // Double
			dout.writeBoolean(true);                 // boolean
			dout.writeChars("Goodbye!");             // 寫入字串
		} catch (IOException e) { }
		
		try {
			fin = new FileInputStream("d:\\temp");
			din = new DataInputStream(fin);
			System.out.println(din.readInt());       // 從檔案中讀取資料到程式中
			System.out.println(din.readLong());
			System.out.println(din.readFloat());
			System.out.println(din.readDouble());
			System.out.println(din.readBoolean());
			char ch;
			while((ch=din.readChar())!='\0') { // 單個字元單個字元讀取,直到末尾
				System.out.print(ch);
			}
			din.close();
		} catch (FileNotFoundException e) { 
			System.out.println("檔案未找到!");
		} catch(IOException e) {
			
		}
	}
}

實驗56:物件的寫入與讀取

編寫一個java程式,在當前資料夾下新建一個檔案ReadWriteObject.txt,往該檔案中寫入兩個學生物件資訊,再從該檔案中讀取這兩個學生物件資訊並顯示

import java.io.*;

class Student implements Serializable{ // 必須對該類序列化,即實現Serializable介面
	String name;
	int age;
	String dept;
	public Student(String newName, int newAge, String newDept){
		name = newName;
		age = newAge;
		dept = newDept;
	}
	public String toString(){
		return name + " " + age + " " + dept;	
	}
}
public class ReadWriteObject{
	public static void main(String[] args){
		Student w1 = new Student("張三", 20, "計算機系");
		Student w2 = new Student("李四", 21, "金融系");
		FileOutputStream fout;
		ObjectOutputStream dout;
		FileInputStream fin;
		ObjectInputStream din;
		File f = new File("ReadWriteObject.txt");
		try{
			f.createNewFile();
		}catch(IOException e){
			System.out.println(e);		
		}
		try{
			fout = new FileOutputStream(f); 
			dout = new ObjectOutputStream(fout); // 建立一個ObjectOutputStream物件
			dout.writeObject(w1);                // 寫入序列化物件
			dout.writeObject(w2);
			dout.close();
		}catch(IOException e){
			System.out.println(e);
		}
		try{
			fin = new FileInputStream(f);
			din = new ObjectInputStream(fin);    // 建立ObjectInputStream物件
			Student r1 = (Student)din.readObject(); // 從檔案中讀取序列化物件
			Student r2 = (Student)din.readObject();
			System.out.println(r1);
			System.out.println(r2);
			din.close();
		}catch(IOException e){
			System.out.println(e);
		}catch(Exception e){
			System.out.println(e);
		}
	}
}

實驗57:對檔案的隨機訪問

編寫一個java程式,在當前資料夾下新建一個檔案RandomFIle.txt,向該檔案中寫入“abcdefghijklmnopqrstuvwxyz”,提示使用者從鍵盤輸入一個0~25之間的整數物件,根據使用者輸入的整數,從檔案中讀取相應的字元並顯示。

import java.util.Scanner;
import java.io.*;
public class MyRandom{
	public static void main(String[] args){
		File f = new File("RandomFile.txt");
		// 新建RandomFile檔案
		try{
			f.createNewFile();			
		}catch(IOException e){
			System.out.println(e);
		}
		String str = "abcdefghijklmnopqrstuvwxyz";
		// 往檔案中寫入資訊
		try{
			FileWriter fw = new FileWriter(f);
			fw.write(str);
			fw.close();
		}catch(IOException e){
			System.out.println(e);
		}
		// 從鍵盤輸入0~25的整數
		int a = -1;
		Scanner sc = new Scanner(System.in);
		while(a<0 | a>25){
			System.out.println("從鍵盤輸入一個0-25的整數:");
			a = sc.nextInt();
		}
		// 隨機訪問檔案中的字元
		try{
			RandomAccessFile inFile = new RandomAccessFile("RandomFile.txt", "r");
			inFile.seek(a); 				// 將檔案指標移動到整數a的位置
			char c = (char)inFile.read();	// 在inFile中讀取一個字元
			inFile.close();
			System.out.println("RandomFile.txt檔案中第"+a+"個字元是"+c);
		}catch(IOException e){
			System.out.println(e);
		}
	}
}

相關推薦

Java輸入輸出IO檔案操作大量例項

java 檔案操作基礎實驗大集合目錄:實驗50:FileInputStream類的應用實驗51:FileOutputStream類應用實驗52:FileReader類的應用實驗53:FileWriter類的應用實驗54:檔案操作 (模版程式)    (1) 學習File類的使

JAVA輸入輸出IO之字元流

上一篇《JAVA輸入輸出(IO)之位元組流》介紹了JAVA位元組輸入輸出流的一些用法,位元組流一般是用於讀寫二進位制資料的,當我們要讀些字元資料的時候,如文字檔案,就顯得有些麻煩。所以JAVA還提供了專門用於讀寫字元資料的字元流。 字元輸入流 java.

java輸入輸出17監控檔案變化

可以通過WatchSercice物件來註冊監聽系統檔案的變化,具體的講解穿插在程式碼中 import java.nio.file.*; public class WatchServiceTest { public static void main(String a

java輸入輸出13 字符集和CharSet

簡而言之,把看得懂字元轉換成看不懂的二進位制數就是編碼,將二進位制數轉換成看得懂的字元就是解碼 字符集其實是很簡單,沒有任何技術難度的,只是為了解決二進位制序列和字元之間的對應關係,需要一個大家都認同的字符集而已。 具體的講解穿插在程式碼中 import java.ni

java輸入輸出14NIO.2

NIO.2是java7對原有的NIO進行了重大改進 這裡首先介紹一下Path,Paths,Files的一些用法,具體的講解穿插在程式碼中 //Path介面代表一個平臺無關的平臺路徑 import java.nio.file.Path; import java.nio.fi

Python基礎集合用法檔案操作字元編碼轉換函式

集合(Set)及其函式 集合是一個無序的、無重複元素的序列。 1 list = {1, 3, 6, 5, 7, 9, 11, 3, 7} # 定義集合方式一 2 list1 = set([1, 3, 6, 5, 7, 9, 11, 3, 7]) # 定義集合方式二 3 list2 = se

java輸入輸出快速

標頭檔案: import java.io.*; 定義: BufferedReader in = new BufferedReader(new InputStreamReader(System.in))

java輸入輸出6退回輸入

java中可以把資料推回輸入流,使得資料可以再次被讀取,以下程式的功能為尋找指定字串“new PushBackReader”,當匹配不到指定字串的時候,將當前遍歷到的字串輸出,如果匹配到指定的字串,將其推回到輸入流,然後再次讀取輸出,具體的程式碼講解穿插在程式碼之中 imp

python基礎之元組檔案操作編碼函式變數 python基礎之元組檔案操作編碼函式變數

python基礎之元組、檔案操作、編碼、函式、變數 1、集合set 集合是無序的,不重複的,主要作用: 去重,把一個列表變成集合,就可以自動去重 關係測試,測試兩組資料的交集,差集,並集等關係 操作例子如下: 1 list_1 = [1,4,5,7,3,6,7,9] 2

JAVA輸入/輸出流程式例題檔案和目錄位元組流字元流

一.檔案和目錄 1.顯示檔案的基本資訊。 2.顯示目錄的基本資訊。 3.在指定目錄下建立單個檔案。 4.指定目錄下建立多個臨時檔案。 二、位元組流 1.生成ZIP壓縮檔案 2.解壓縮zip檔案 3.生成Excel檔案 4.讀取excel檔案 5.生成PDF檔案 6.讀取P

java輸入輸出10:IOIO流概述及其分類

1 概念 1、IO流用來處理裝置之間的資料傳輸。 2、Java對資料的操作時通過流的方式。 3、Java用於操作流的類都在IO包中。 4、流按流向分為兩種:輸入流,輸出流。 5、流按照操作型別分為兩種:(1)位元組流:位元組流可以操作任何資料,因為在計算機中任何資料都是以位元

C ++基礎 | 格式化輸出檔案輸入輸出File IO,標頭檔案Header Files_3

目錄 格式化輸出 檔案輸入輸出(File IO) 標頭檔案(Header Files) 格式化輸出 要格式化資料,我們可以使用轉義字串(Escape Sequence)也稱字元實體(Character Entity)。這些不需要任何額外的庫。 C ++ 轉義字串

java輸入輸出11:IOFileOutputStream

FileOutputStream(String str)在建立物件的時候沒有這個檔案會建立該檔案,如果有這個檔案就會將其清空。 package filePackage; import java.io.F

java輸入輸出12:IO拷貝圖片

第1種實現方式 package filePackage; import java.io.FileInputStream; import java.io.FileNotFoundException; im

java輸入輸出13:IOBufferedInputStream和BufferedOutputStream拷貝

緩衝思想 位元組流一次讀寫一個數組的速度明顯比一次讀寫一個位元組的速度快很多,這是加入了陣列這樣的緩衝區的效果。 BufferedInputStream BufferedInputStream中讀取一個緩衝區(陣列),從BufferedInputStream中讀

java輸入輸出14:IO位元組流讀寫中文

位元組流讀取中文的問題 位元組流在讀中文的時候有可能會讀到半個中文,造成亂碼。 位元組流寫出中文的問題 位元組流直接操作位元組,所以寫出中文必須將字串轉換成位元組陣列。寫出回車換行write("\r\n

Java 基礎-IOstream 流檔案操作

輸入輸出流的分類 在 java.io 包中,包含了輸入輸出操作所需的類。 I/O 流可以安裝不同的標準分類: 按照流的方向分類: 輸入流:將資訊從程式碼外部輸入程式碼 輸出流:將程式碼得到的資料輸出到檔案、網路、記憶體等地方

java輸入輸出流詳細講解入門經典,詳細講解JAVA中的IO

今天我們開始進入學習 java 中比較讓人頭疼的事, 那就是 I/O 流、多執行緒、網路程式設計。這裡對 I/O 流的一個詳細講解。希望對大家有點用吧。(不看後悔哦) 一、什麼是IO Java中I/O操作主要是指使用Java進行輸入,輸出操作。 Java所有的I/O機制都是基於資料流進行輸入

【代碼筆記】Java文件的輸入輸出1——Java.io包的初步理解

對象 eclips 是什麽 reader optional 傳輸 gre 用戶界面 cep Java裏面文件的輸入輸出全部在java.io包裏面。 Java.io包裏面所有的類都需要掌握。 java.io包裏面所有的東西都在上面了。 包裏面的相關類

程式碼中的輸入輸出重定向檔案流C/C++

一.freopen的使用(C/C++) 函式原型:FILE *freopen( const char *path, const char*mode, FILE *stream ); 標頭檔案: std