Java文件的I/O流

1.File对象

File file=new File(String pathName);

pathName指向的文件的路径

public class FileMethod {
	/**
	 * 显示文件信息
	 * @param file 文件对象
	 * */
	public 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("文件不存在");
		}
	}
	
}

2.流

    输入流:只能从中读取数据,而不能向其中写入数据。

    输出流:只能从中写数据,而不能读数据。

    JAVA的输出流主要由OutputStream和Writer作为基类, 而输入流则主要由InputStream和Reader作为基类。

流可以分为字节流和字符流

    字节流操作最小数据单元为8位的字节,而字符流操作的最小数据单位是16位的字符。

字节输入流InputStream,字节输出流OutputStream。

字符输入流Reader基类,字符流输出Writer

读写文件

/**
 * 字符流输入和输出
 * */
public class Test15 {
	public static void main(String[] args) {
		Writer w=null;
		try {
			w=new FileWriter("C:/c.txt");
			BufferedWriter bw=new BufferedWriter(w);
			bw.write("你好世界!");
			bw.newLine();//换行
			bw.write("惊天其二");
			bw.flush();//刷新动作
			
			Reader r=new FileReader("C:/c.txt");
			BufferedReader br=new BufferedReader(r);
			String line=br.readLine();
			//判断是否为空
			while(line!=null){
				System.out.println(line);
				line=br.readLine();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

案例

//读文件的方法
	public String readFile(String filePath) {
		//定义读文件的
		Reader r=null;
		BufferedReader bf=null;
		try {
			r=new FileReader(filePath);
			bf=new BufferedReader(r);
			String line=bf.readLine();
			//定义一个临时的String好返回
			String temp="";
			while(line!=null){
				temp=temp+line+"\n";
				line=bf.readLine();
			}
			//返回读取文件
			return temp;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(bf!=null){bf.close();}
				if(r!=null){r.close();}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	//写文件的方法
	public void writeFile(String filePath,String str) {
		//写文件的方法
		Writer w=null;
		BufferedWriter bw=null;
		try {
			w=new FileWriter(filePath);
			bw=new BufferedWriter(w);
			bw.write(str);
			bw.flush();				//刷新动作
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			//关闭
			try {
				if(bw!=null){bw.close();}
				if(w!=null){w.close();}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/qq_41632129/article/details/80383088