• 通过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();
    	}
    

      终极版

  • 相关阅读:
    C++ CGI Helloword
    国内外12个免费域名解析服务网站推荐
    U制作LFS linux
    LFS 中文版手册发布:如何打造自己的 Linux 发行版
    windows下的BT服务器搭建方案
    Linux下搭建BT服务器
    Codeforces 842B Gleb And Pizza【几何,水】
    Codeforces 842A Kirill And The Game【暴力,水】
    Wannafly模拟赛 A.矩阵(二分答案+hash)
    数据结构学习笔记【持续更新】
  • 原文地址:https://www.cnblogs.com/xpqsd/p/6133827.html
Copyright © 2020-2023  润新知