文件操作:读取,保存,导入,导出文件功能实现

导读:本篇文章讲解 文件操作:读取,保存,导入,导出文件功能实现,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

前言

记录一次对文件的操作实现,从前端到后端:用的是若依框架,但是功能是自己实现的。

1.需求

1.如图有2个输入框和1个选择器,填写好内容后点击下一步就会保存到文件里面。
在这里插入图片描述
3个数据用”,”号分割,存到文本。
如下图:
在这里插入图片描述

2.前端实现

页面代码.vue

<el-form ref="form" :inline="true" :model="form" class="demo-form-inline" >
             <span class="span">(此处发生变化时,点击下一步生效)</span>
                <div class="btnTool" style="text-align: right">
          <el-button type="success" size="mini" @click="addHeader"
            >新增</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="importFile"
            >导入</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="exportFile"
            >导出</el-button
          >
        </div>
        <el-divider></el-divider>


        <div v-for="(item, index) in form.headers" :key="index">
          <el-form-item label="ip" :prop="'headers.' + index + 'ip'">
            <el-input v-model="item.ip" placeholder="ip"></el-input>
          </el-form-item>
          <el-form-item label="端口号" :prop="'headers.' + index + 'port'">
            <el-input v-model="item.port" placeholder="端口号"></el-input>
          </el-form-item>
          <el-form-item label="类型" :prop="'headers.' + index+ 'type'">
            <el-select v-model="item.type" placeholder="类型">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-link
              type="primary"
              :underline="false"
              @click.prevent="removeHeader(item, index)"
              >删除</el-link
            >
          </el-form-item>
        </div>
        <div>
        <el-divider></el-divider>

        <el-button type="success" size="mini" style="display:block;margin:0 auto" @click="onSubmit">下一步</el-button>
        </div>
      </el-form>

       <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls, .txt"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <!-- <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据 -->
          </div>
          <span>仅允许导入cfg格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

方法methods

//添加
 addHeader() {
      this.form.headers.push({
        ip: "",
        port: "",
        type: "",
      });
    },
   // 删除
    removeHeader(item, index) {
      this.form.headers.splice(index, 1);
    },
    handleClick(tab, event) {
    //  console.log(tab, event);
    },
  //下一步
    onSubmit(){
      console.log(this.form)
      submitMirror(this.form.headers).then(response => {
       // console.log(response);
      })
      this.activeName = "second"
    },
//查询文件里的数据并展示
    getList(){
      console.log("getList");
      readMirror().then(response => {
    //   console.log(response.data);
        this.form.headers = response.data;
      });
    },
    importFile(){
      console.log("importMirror导入方法");
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    exportFile(){
      console.log("exportFile导出方法");
      this.download('config/export',{
        ...this.form.headers
      },'a.txt')
    },
        // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
     /** 下载模板操作 */
    // importTemplate() {
    //   this.download('system/user/importTemplate', {
    //   }, `user_template_${new Date().getTime()}.xlsx`)
    // },
    // 提交上传文件
    submitFileForm() {

      this.$refs.upload.submit();
    },

3.后端接口

1.实体类

@Data
public class Mirror {
    private String ip;
    private String port;
    private String type;
}

2.service层(业务)

因为这里没有去访问数据库,所以就没有mapper.xml了。 主要业务代码写在serviceImpl层里面,所以这里只展示这一层的代码。

@Slf4j
@Service
public class MirrorServiceImpl implements MirrorService {
    String path = "D:\\address.txt";

    public MirrorServiceImpl() {
    }

    public AjaxResult mirror(List<Mirror> headers) {
    	//用流将接受到的对象各个属性用","连接,在形成新的list集合
        List<String> address = (List)headers.stream().map((item) -> {
            return item.getIp() + "," + item.getPort() + "," + item.getType();
        }).collect(Collectors.toList());
        //创建一个文件
        File outFile = new File(this.path);

        try {
            if (!outFile.exists()) {
                outFile.createNewFile();
            }
			//创建文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream(outFile);
            //加锁:可省略
            FileChannel fc = fileOutputStream.getChannel();
            FileLock fileLock = fc.lock();
            if (fileLock != null) {
                log.info("有其他线程正在操作此文件,当前线程休眠10秒");
            }

            Iterator var7 = address.iterator();
			//遍历集合,将集合内容写入文件内
            while(var7.hasNext()) {
                String s = (String)var7.next();
                byte[] bytes = s.getBytes();
                fileOutputStream.write(bytes);
                //换行
                fileOutputStream.write("\r\n".getBytes());
            }

            fileLock.release();
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException var10) {
            var10.printStackTrace();
        }

        return AjaxResult.success("保存成功");
    }

    public AjaxResult read() {
        List<String> list = new ArrayList();
        ArrayList mirrors = new ArrayList();

        try {
            FileReader fileReader = new FileReader(this.path);
            //缓冲流,能提高效率,使用时要传入一个fileReader字符输入流
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String lineString = "";
			//定义一个空串,将文本的内容读到这个字符串中,在加入到集合里面
            while(null != (lineString = bufferedReader.readLine())) {
                list.add(lineString);
            }

            bufferedReader.close();
            fileReader.close();
        } catch (FileNotFoundException var7) {
            var7.printStackTrace();
        } catch (IOException var8) {
            var8.printStackTrace();
        }

        Iterator var9 = list.iterator();
		//这里我们前端接受的数据是没有”,“号的,所以我们这里用split进行切割
		//在把内容设置到对象里面,将对象传入集合中返回给前端
        while(var9.hasNext()) {
            String s = (String)var9.next();
            String[] split = s.split(",");
            Mirror mirror = new Mirror();
            mirror.setIp(split[0]);
            mirror.setPort(split[1]);
            mirror.setType(split[2]);
            mirrors.add(mirror);
        }

        return AjaxResult.success("读取成功", mirrors);
    }

    public AjaxResult export(HttpServletRequest request, HttpServletResponse response) {
        File file = new File(this.path);
        //设置字符编码
        response.setCharacterEncoding("UTF-8");
        String realFilename = file.getName();
        //设置请求头
        response.setHeader("content-type", "application/octet-stream;charset=UTF-8");
        response.setContentType("application/octet-stream;charset=UTF-8");
        if (file.exists()) {
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realFilename.trim(), "UTF-8"));
                BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
                BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                byte[] bytes = new byte[2048];

                int byteSize;
                while((byteSize = inputStream.read(bytes, 0, bytes.length)) != -1) {
                    outputStream.write(bytes, 0, byteSize);
                }

                inputStream.close();
                outputStream.close();
            } catch (UnsupportedEncodingException var9) {
                var9.printStackTrace();
            } catch (FileNotFoundException var10) {
                var10.printStackTrace();
            } catch (IOException var11) {
                var11.printStackTrace();
            }
        }

        return null;
    }

    public AjaxResult importFile(MultipartFile file) {
        try {
            InputStream is = file.getInputStream();
            FileOutputStream fos = new FileOutputStream(new File(this.path));
            FileChannel fileChannel = fos.getChannel();
            FileLock lock = fileChannel.lock();
            if (lock != null) {
                log.info("有其他线程正在操作此文件,当前线程休眠10秒");
            }

            byte[] buffer = new byte[2048];
            boolean var7 = false;

            int byteSize;
            while((byteSize = is.read(buffer, 0, buffer.length)) != -1) {
                fos.write(buffer, 0, byteSize);
            }

            lock.release();
            fos.flush();
            fos.close();
            is.close();
        } catch (IOException var8) {
            var8.printStackTrace();
        }

        return AjaxResult.success("导入成功");
    }
}

保存文件

public AjaxResult mirror(List<Mirror> headers) {
    	//用流将接受到的对象各个属性用","连接,在形成新的list集合
        List<String> address = (List)headers.stream().map((item) -> {
            return item.getIp() + "," + item.getPort() + "," + item.getType();
        }).collect(Collectors.toList());
        //创建一个文件
        File outFile = new File(this.path);

        try {
            if (!outFile.exists()) {
                outFile.createNewFile();
            }
			//创建文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream(outFile);
            //加锁:可省略
            FileChannel fc = fileOutputStream.getChannel();
            FileLock fileLock = fc.lock();
            if (fileLock != null) {
                log.info("有其他线程正在操作此文件,当前线程休眠10秒");
            }

            Iterator var7 = address.iterator();
			//遍历集合,将集合内容写入文件内
            while(var7.hasNext()) {
                String s = (String)var7.next();
                byte[] bytes = s.getBytes();
                fileOutputStream.write(bytes);
                //换行
                fileOutputStream.write("\r\n".getBytes());
            }

            fileLock.release();
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException var10) {
            var10.printStackTrace();
        }

        return AjaxResult.success("保存成功");
    }

读取文件内容展示

 public AjaxResult read() {
        List<String> list = new ArrayList();
        ArrayList mirrors = new ArrayList();

        try {
            FileReader fileReader = new FileReader(this.path);
            //缓冲流,能提高效率,使用时要传入一个fileReader字符输入流
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String lineString = "";
			//定义一个空串,将文本的内容读到这个字符串中,在加入到集合里面
            while(null != (lineString = bufferedReader.readLine())) {
                list.add(lineString);
            }

            bufferedReader.close();
            fileReader.close();
        } catch (FileNotFoundException var7) {
            var7.printStackTrace();
        } catch (IOException var8) {
            var8.printStackTrace();
        }

        Iterator var9 = list.iterator();
		//这里我们前端接受的数据是没有”,“号的,所以我们这里用split进行切割
		//在把内容设置到对象里面,将对象传入集合中返回给前端
        while(var9.hasNext()) {
            String s = (String)var9.next();
            String[] split = s.split(",");
            Mirror mirror = new Mirror();
            mirror.setIp(split[0]);
            mirror.setPort(split[1]);
            mirror.setType(split[2]);
            mirrors.add(mirror);
        }

        return AjaxResult.success("读取成功", mirrors);
    }

导入导出功能

//导出功能
    public AjaxResult export(HttpServletRequest request, HttpServletResponse response) {
        File file = new File(this.path);
        //设置字符编码
        response.setCharacterEncoding("UTF-8");
        String realFilename = file.getName();
        //设置请求头
        response.setHeader("content-type", "application/octet-stream;charset=UTF-8");
        response.setContentType("application/octet-stream;charset=UTF-8");
        if (file.exists()) {
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realFilename.trim(), "UTF-8"));
                BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
                BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                byte[] bytes = new byte[2048];

                int byteSize;
                while((byteSize = inputStream.read(bytes, 0, bytes.length)) != -1) {
                    outputStream.write(bytes, 0, byteSize);
                }

                inputStream.close();
                outputStream.close();
            } catch (UnsupportedEncodingException var9) {
                var9.printStackTrace();
            } catch (FileNotFoundException var10) {
                var10.printStackTrace();
            } catch (IOException var11) {
                var11.printStackTrace();
            }
        }

        return null;
    }
//导入功能实现
    public AjaxResult importFile(MultipartFile file) {
        try {
        //file为前端选择的文件,创建输入流
            InputStream is = file.getInputStream();
            //创建一个输出流
            FileOutputStream fos = new FileOutputStream(new File(this.path));
            FileChannel fileChannel = fos.getChannel();
            FileLock lock = fileChannel.lock();
            if (lock != null) {
                log.info("有其他线程正在操作此文件,当前线程休眠10秒");
            }

            byte[] buffer = new byte[2048];
            boolean var7 = false;

            int byteSize;
            while((byteSize = is.read(buffer, 0, buffer.length)) != -1) {
                fos.write(buffer, 0, byteSize);
            }

            lock.release();
            fos.flush();
            fos.close();
            is.close();
        } catch (IOException var8) {
            var8.printStackTrace();
        }

        return AjaxResult.success("导入成功");
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/111660.html

(0)
Java光头强的头像Java光头强

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!