• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

徐培淇

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

通过InputStream访问文件中的数据的四种方法

//方法一(每次只读取一个字节)
	public static void getFile() throws IOException {
		
		File file = new File("D:\\a.txt");
		
		FileInputStream fileinputstream = new FileInputStream(file);
		
		int data = fileinputstream.read();
		int data1 = fileinputstream.read();
		
		System.out.println("获取的数据"+data1);
		fileinputstream.close();
		
		
	}

  只是输出目标文件的第一个字符,所以说很不实用

//方法二

public static void getFile2() throws IOException {
		File file = new File("D:\\a.txt");
		
		FileInputStream fileInputStream = new FileInputStream(file);
		
		for (int i = 0; i <file.length(); i++) {
	
			System.out.print((char)fileInputStream.read());
		}
		fileInputStream.close();
	}

通用步骤:

  1.找到目标文件:注意操作的是文件而不是文件夹(切记!!!!!)

  2.建立通道

  3.[创建缓冲区]

  4.读取数据:read()只获取一个字节

  5.释放之原文件

  

需要不断地运行一个循环内存占用过大

public static void getFile3() throws IOException {
		File file = new File("D:\\a.txt");
		
		FileInputStream fileInputStream = new FileInputStream(file);
		
		byte[] b = new byte[(int) file.length()];
		
		int count = fileInputStream.read(b);
		
		System.out.println(count);
		
		System.out.println(new String(b));
		
		fileInputStream.close();
		
		
	}

  

	public static void getFile4() throws IOException {
		
		File file = new File("D:\\java\\第十八次课\\代码\\Day18\\src\\com\\beiwo\\File\\Demo1.java");                       
		
		FileInputStream fileInputStream = new FileInputStream(file);
		
		byte[] b = new byte[1024];
		
		int count = 0;
		
		while ((count = fileInputStream.read(b))!= -1) {
		System.out.println(new String(b,0,count));
			
		}
		
		fileInputStream.close();
	}

  终极版

posted on 2016-12-05 14:32  徐培淇  阅读(2349)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3