Java读取文件的方法

た 入场券 2022-05-11 14:44 279阅读 0赞

读取二进制文件

读取二进制文件,并存入byte数组,如算法训练模型的二进制模型。

  1. public byte[] readFromByteFile(String pathname) throws IOException{
  2. File filename = new File(pathname);
  3. BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
  4. ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
  5. byte[] temp = new byte[1024];
  6. int size = 0;
  7. while((size = in.read(temp)) != -1){
  8. out.write(temp, 0, size);
  9. }
  10. in.close();
  11. byte[] content = out.toByteArray();
  12. return content;
  13. }

读取文本文件

读取文本文件,每次读取文件一行内容,并把结果存入字符串数组。

  1. public ArrayList<String> readFromTextFile(String pathname) throws IOException{
  2. ArrayList<String> strArray = new ArrayList<String>();
  3. File filename = new File(pathname);
  4. InputStreamReader reader = new InputStreamReader(new FileInputStream(filename));
  5. BufferedReader br = new BufferedReader(reader);
  6. String line = "";
  7. line = br.readLine();
  8. while(line != null) {
  9. strArray.add(line);
  10. line = br.readLine();
  11. }
  12. return strArray;
  13. }

发表评论

表情:
评论列表 (有 0 条评论,279人围观)

还没有评论,来说两句吧...

相关阅读