S2 第八章_Fil I/O

import java.io.File;//  I/O input 输入 output 输出
File file = new File("d:/123.txt");//指向这个文件(文件路径)
		System.out.println(file.getName());//名字
		System.out.println(file.getPath());//相对路径
		System.out.println(file.getAbsolutePath());//绝对路径
		System.out.println(file.getParent());//上级路径
                System.out.println(file.length());//字节长度
                System.out.println(file.exists());//判断文件是否存在
                System.out.println(file.isFile());//是不是文件
	        System.out.println(file.isDirectory());//是不是文件夹
try {
						file.createNewFile();//创建一个同名空白文件
					} catch (Exception e) {
						// TODO: handle exception
					}
					file.delete()//删除

读文件是指把文件的数据读取到内存

InputStream is = new FileInputStream(file);
			System.out.println((char)is.read());//读取第一个字

写文件是指把内存的数据写入文件


读数据用输入流

File file = new File("d:/123.txt");
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			byte [] bs = new byte[5];
			int length = is.read(bs);
			
			while (length != -1) {//避免一直循环
				for (byte b : bs) {//读出的数据放在bs数组中了
					System.out.print((char)b);//读取第一个字
				}
				length = is.read(bs);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

写数据用输出流

try {
			os.write("123456".getBytes(),3,2);//从下标为三开始添加  ,添加几个
			os.write("123456".getBytes(),0,"123456".length());

字符流:

public class Test_10 {
	public static void main(String[] args) {
		Writer writer = null;
		try {
			writer = new FileWriter(new File("d:/123.txt"));
			writer.write(97);
			writer.flush();//刷新
		} catch (IOException e) {
			
			e.printStackTrace();
		}finally{
			try {
				writer.close();
			} catch (IOException e) {
				
				e.printStackTrace();
			}
		}
	}
}

二进制读文件:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值