根据内容生成文件

  1. /**
  2. * 根据内容生本文件
  3. *
  4. * @param filePath 本地路径
  5. * @param scriptContent 内容
  6. * @author YangYudi
  7. * @date 2021/1/8 17:16
  8. */
  9. public static void writerFile(String filePath, String scriptContent) {
  10. //生成脚本 false表示不追加
  11. try (Writer writer = new FileWriter(filePath, false);
  12. BufferedWriter bufferedWriter = new BufferedWriter(writer)) {
  13. bufferedWriter.write(scriptContent);
  14. bufferedWriter.flush();
  15. writer.flush();
  16. } catch (IOException e) {
  17. log.error(e.getMessage());
  18. }
  19. }

根据输入流生成文件

  1. public void inputStreamToFile(InputStream inputStream) {
  2. try {
  3. //新建文件
  4. File file = new File("demo.docx");
  5. if (file.exists()) {
  6. file.createNewFile();
  7. }
  8. OutputStream os = new FileOutputStream(file);
  9. int read = 0;
  10. byte[] bytes = new byte[1024 * 1024];
  11. //先读后写
  12. while ((read = inputStream.read(bytes)) > 0) {
  13. byte[] wBytes = new byte[read];
  14. System.arraycopy(bytes, 0, wBytes, 0, read);
  15. os.write(wBytes);
  16. }
  17. os.flush();
  18. os.close();
  19. inputStream.close();
  20. } catch (Exception e) {
  21. e.printStackTrace();
  22. }
  23. }