Home > Java > JavaBase > body text

How to save files locally in java

王林
Release: 2019-11-23 13:28:02
Original
11629 people have browsed it

How to save files locally in java

知识补充:

File类以抽象的方式代表文件名和目录路径名,该类主要用于文件和目录的创建、文件的查找和文件的删除等。

FileOutputStream类用来创建一个文件并向文件中写数据,如果该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件。

保存方法:

首先根据要保存的文件路径创建一个文件对象,然后通过“exists”方法判断文件是否存在,若不存在则新建文件,若存在则开始通过“FileOutPutStream”类创建新文件并向该文件中写入数据即可。

示例如下:

private void savePic(InputStream inputStream, String fileName) {
    OutputStream os = null;
    try {
      String path = "D:\\testFile\\";
      // 2、保存到临时文件
      // 1K的数据缓冲
      byte[] bs = new byte[1024];
      // 读取到的数据长度
      int len;
      // 输出的文件流保存到本地文件
      File tempFile = new File(path);
      if (!tempFile.exists()) {
        tempFile.mkdirs();
      }
      os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
      // 开始读取
      while ((len = inputStream.read(bs)) != -1) {
        os.write(bs, 0, len);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // 完毕,关闭所有链接
      try {
        os.close();
        inputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Copy after login

推荐教程:java开发入门

The above is the detailed content of How to save files locally in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template