File类读取文件—本地文件和网络文件

  • Post author:
  • Post category:其他


读取本地文件:

        File file = new File("./resource/audio/5.mp3");
		InputStream in = null;
		try {
			// 一次读多个字节
			byte[] tempbytes = new byte[100];
			int byteread = 0;
			in = new FileInputStream(file);
			// 读入多个字节到字节数组中,byteread为一次读入的字节数
			while ((byteread = in.read(tempbytes)) != -1) {
				System.out.write(tempbytes, 0, byteread);
			}
			System.out.println("文件大小===="+file.length());
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
				}
			}
		}

读取网络文件输出字节数组:(

http://localhost:8080/1.txt

    private static byte[] openFile(String filePath) {
        int HttpResult; // 服务器返回的状态
        byte[] bytes = new byte[SLICE_SICE];
        try
        {
            URL url =new URL(filePath); // 创建URL
            URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码
            urlconn.connect();
            HttpURLConnection httpconn =(HttpURLConnection)urlconn;
            HttpResult = httpconn.getResponseCode();
            if(HttpResult != HttpURLConnection.HTTP_OK) {
                System.out.print("无法连接到");
            } else {
                int filesize = urlconn.getContentLength(); // 取数据长度
                System.out.println("取数据长度===="+filesize);
                urlconn.getInputStream();
                InputStream inputStream = urlconn.getInputStream();
                
                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                int ch;
                while ((ch = inputStream.read()) != -1) {   
                    swapStream.write(ch);   
                }
                bytes = swapStream.toByteArray();
            }
            System.out.println("文件大小===="+bytes.length);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return  bytes;
    }



版权声明:本文为qq_33581278原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。