File I/O

本文详细介绍Java中文件和流的基本概念,包括File类的使用、输入输出流的分类及应用,以及如何使用字节流和字符流进行文本文件的读写。同时,介绍了二进制文件的读写方法。

File/IO

一、使用File类操作文件或目录属性

1、File类的构造函数:

File (String path):根据路径得到File对象

File(String parent,String child):根据一个目录和一个子文件/目录得到File对象

File(File parent,String child):根据一个父File对象和一个子文件得到File对象

2、File类的常用方法:

public String getAbsolutePath():获取绝对路径

public String getPath():获取路径

public String getName():获取文件或者目录的名称

public String getParent():获取上层文件目录路径,若无返回null

public long length():获取文件的长度,单位为字节

public long lastModified():获取最后一次修改时间(毫秒值)

public boolean renameTo(File dest):文件重命名

public boolean isDirectory():判断是否是文件目录

public boolean isFile():判断是否是文件

public boolean exists():判断文件或者目录是否存在

public boolean canRead():判断是否可读

public boolean canWrite():判断是否可写

public boolean isHidden():判断是否隐藏

public boolean createNewFile():创建文件

public boolean mkdir():创建文件目录

public boolean mkdirs():创建多个文件目录

public boolean delete():删除文件或文件夹(如果文件夹内有文件则删除失败)

3、File类的使用

public class FileMethods {
	public static void main(String[] args) {
		File file =new File("路径");
		FileMethods.showFileInfo(file);
		File file2 =new File("路径");
		FileMethods.create(file2);
		FileMethods.delete(file2);
	}
	
	//创建文件
	public static void create(File file) {
		if(!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("文件已经创建!");
		}
	}
	
	//删除文件
	public static void delete(File file) {
		if(file.exists()) {
			file.delete();
			System.out.println("文件已经删除!");
		}
	}
	
	
	//查看文件属性
	public static void showFileInfo(File file) {
        //判断文件或者目录是否存在
		if(file.exists()) {
			if(file.isFile()) {
				System.out.println("名称:"+file.getName());
				System.out.println("相对路径:"+file.getPath());
				System.out.println("绝对路径:"+file.getAbsolutePath());
				System.out.println("文件大小:"+file.length());
			}
			if(file.isDirectory()) {
				System.out.println("此文件是目录!");
			}
		}else {
			System.out.println("文件不存在!");
		}
	}
}

二、Java的流

1、流的概念:流,是指一连串流动的字符,是以先进先出的方式发送和接收数据的通道。

输入Input:读取外部数据(磁盘等存储设备)的数据到程序(内存)。

输出Output:将程序(内存)数据输出到硬盘等存储设备中。

2、流的分类:

①按照方向区分:输入流和输出流

②按照大小区分:字节流(8 bit)和字符流(16 bit)

注意:字符流能实现的功能,字节流都能实现,反之不一定。

三、读写文本文件

一、使用字节流读取文本文件

1、字节输入流InputStream类(抽象基类)

常用方法:

方法名称说明
int read()读取一个字节数据
int read(byte [] b)将数据读取到字节数组中
int read(byte[] b,int off,int len)从输入流中读取最多len长度的字节,保存到字节数组b中,保存的位置从off开始
void close()关闭输入流
int available()返回输入流读取的估计字节数

2、字节输入流FileInputStream类(子类)

构造函数:

(1)FileInputStream(File file),其中file指定文件数据源

File file =new File("C:\\hello.txt");
FileInputStream fis =new FileInputStream(file);

(2)FileInputStream(String name),其中name指定文件数据源

FileInputStream fis =new FileInputStream("C:\\hello.txt");

3、FileInputStream类读取文件使用步骤:

①导包:java.io.*;

②创建一个文件输入流对象:FileInputStream fis =new FileInputStream(“C:\hello.txt”);

③执行读取文件的操作:fis.read(); //读取文件的数据

④关闭文件输入流对象:fis.close();

【总结】文件读写的步骤:

①导包

②创建流对象

③执行读写操作

④关闭相关流对象

FileInputStream fis =null;
try {
		fis =new FileInputStream("路径");
		int data;
		System.out.println("可读取的字节数:"+fis.available());
		System.out.println("文件内容为:");
		while((data=fis.read())!=-1) {
			System.out.print((char)data);
		}
}catch(IOException e) {
		e.printStackTrace();
}finally {
		try {
			if(fis!=null) {
				fis.close();
			}
        }catch (IOException e) {
			e.printStackTrace();
		}
}
二、使用字节流写入文本文件

1、字节输出流OutputStream类(抽象基类)

方法名称说明
void write(int c)写入一个字节数据
void write(byte [] buf)写入数组buf的所有字节
void write(byte [] b,int off,int len)将字节数组中从off位置开始,长度为len的字节数据输出到输出流中
void close()关闭输出流

2、字节输出流FileOutputStream类(子类)

FileOutputStream类和FileInputStream类的构造函数相同,使用的步骤也是一样的,区别在于FileOutputStream类是输出,FileInputStream类是输入。

FileOutputStream fos =null;
try {
	String str="好好学习Java";
	byte [] words =str.getBytes();
	fos =new FileOutputStream("E:\\S2作业\\JavaOOP\\Ch08\\hello.txt",true);  //true表示追加,没有写则是覆盖
	fos.write(words, 0, words.length);
	System.out.println("hello文件已经更新!");
} catch (IOException e) {
	e.printStackTrace();
}finally {
	try {
		if(fos!=null) {
			fos.close();
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}
三、使用字符流读取文本文件

1、字符输入流Reader类(抽象基类)

方法名称说明
int read()从输入流中读取单个字符
int read(byte [] c)从输入流中读取c.length长度的字符,保存到字符数组c中,返回实际读取的字符数
int read(byte [] c,int off ,in len)从输入流中读取最多len长度的字符,保存到字符数组c中,保存的位置从off位置开始,返回实际读取的字符长度
void close()关闭流

2、字符输入流FileReader类(子类)

①构造函数

FileReader(String fileName):fileName是指要从中读取数据的文件的名称

Reader fr =new FileReader("路径");

②FileReader类读取文件步骤

import java.io.*; //①导包
Reader fr = null;
StringBuffer sbf = null;
try {
    //②创建FileReader对象
	fr =new FileReader("路径");
	char ch [] =new char[1024];
	sbf =new StringBuffer();
    //③执行读取操作
	int length =fr.read(ch);
	while (length!=-1) {
		sbf.append(ch);
		length =fr.read();
	}
}catch(IOException e) {
	e.printStackTrace();
}finally {
	try {
		if(fr!=null) {
			fr.close();   //④关闭相关的流对象
		}
	 catch (IOException e) {
		e.printStackTrace();
	 }
}
System.out.println(sbf.toString());

3、字符输入流BufferedReader类(子类)

它与FileReader类的区别在于BufferedReader类带有缓冲区,它可以先把一批数据读到缓冲区,然后从缓冲区内获取数据,避免每次都从数据源读取数据进行字符编码转换,所以BufferedReader类读取操作效率更高。

读取的步骤:

①导包

②创建一个BufferedReader对象

Reader fr =new FileReader("路径");
BufferedReader br =new BufferedReader(fr);

③执行读取文件的操作

br.readLine();  //读取一行数据,返回字符串

④关闭相关的流对象

四、使用字符流写文本文件

1、字符输出流Writer类(抽象基类)

方法名称说明
write(String str)将str字符串里包含的字符输出到指定的输出流中
Write(String str,int off ,int len)将str字符串里从off位置开始长度为len的字符输出到输出流中
voud flush()刷新输出流
void close()关闭输出流

2、字符输出流FileWriter类(子类)

Writer fw =null;
try {
	fw =new FileWriter("路径");
	fw.write("我热爱我的团队!");
	fw.flush();  ///刷新缓冲区
} catch (IOException e) {
	e.printStackTrace();
}finally{
	try {
		if(fw!=null) {
			fw.close();
		}
    }catch (IOException e) {
		e.printStackTrace();
	}
}

3、字符输出流BufferedWriter类(子类)

BufferedWriter是把一批数据写到缓冲区,当缓冲区满的时候再把缓冲区的数据写到字符输出流中,可以避免每次都执行物理写操作,提高了操作的效率。

使用步骤和BufferedReader类一样,关键字不同,这里不再多说。

三、二进制文件的读写

一、使用字节流类DataInputStream读二进制文件

步骤:

①导包

②创建对象

FileInputStream fis =new FileInputStream("路径");
DataInputStream dis =new DataInputStream(fis);

③执行读取操作

dis.read();  //读取数据字节

④关闭数据输入流

二、使用字节流类DataOutputStream写二进制文件

步骤:

①导包

②创建对象

FileOutputStream fos =new FileOutputStream("路径");
DataOutputStream dos =new DataOutputStream(fos);

③执行写入操作

dos.write(1);   //将指定字节数据写入二进制文件

④关闭数据输出流

为什么学习?

因为操作基本数据类型,保证字节原样性。

try{
	DataOutputStream out=new DataOutputStream(new FileOutputStream(filename));
	out.writeInt(30);
	out.writeByte(1);
	out.writeChar('c');
    out.writeUTF("hello");
    out.writeLong(2);
	out.close();
}catch(IOException e){
	e.printStackTrace();
}
try{
	DataInputStream in=new DataInputStream(new FileInputStream(filename));
	System.out.println(in.readByte());
    System.out.println(in.readLong());
    System.out.println(in.readChar());
    System.out.println(in.readUTF());
	in.close();
}catch(IOException e){
	e.printStackTrace();
}
To build a VI in LabVIEW that generates a 3x100 2D array of random numbers, transposes the data, and writes it to a spreadsheet file with column headers using high - level File I/O VIs from the Functions»File I/O palette, follow these steps: ### Step 1: Create a new VI Open LabVIEW and create a new Virtual Instrument (VI). ### Step 2: Generate the 3x100 2D array of random numbers - From the Functions palette, navigate to Programming»Numeric»Random Number (0 - 1). Place three instances of this function on the block diagram. - Use the Build Array function (found in Programming»Array) to combine these three 1D arrays of 100 elements each into a 2D array of 3 rows and 100 columns. ```plaintext Random Number (0 - 1) ---> Build Array Random Number (0 - 1) ---> Build Array Random Number (0 - 1) ---> Build Array ``` ### Step 3: Transpose the 2D array - Place the Transpose 2D Array function (found in Programming»Array) on the block diagram. Connect the output of the Build Array function to the input of the Transpose 2D Array function. ### Step 4: Define column headers - Use the String Constants from the Functions palette (Programming»String) to create strings for each column header. For example, if you have 3 columns, create three string constants like "Column 1", "Column 2", "Column 3". - Use the Build Array function again to create a 1D array of these string constants. This will represent the header row. ### Step 5: Combine the header row and the transposed data - Use the Concatenate Arrays function (found in Programming»Array) to combine the 1D array of headers and the transposed 2D array. This will create a new 2D array with the headers as the first row. ### Step 6: Write the data to a spreadsheet file - From the Functions palette, go to Functions»File I/O. Use the Write to Spreadsheet File VI. - Connect the output of the Concatenate Arrays function to the Array input of the Write to Spreadsheet File VI. - Specify the file path where you want to save the spreadsheet file using a Path control (found in Controls»Modern»String). Connect this path control to the File Path input of the Write to Spreadsheet File VI. ### Step 7: Run the VI - Click the Run button on the toolbar to execute the VI. The generated random data with column headers will be written to the specified spreadsheet file.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值