Reading from a file using DataInputStream is very slow

I have a file containing a large number of numbers.

I tried using the following code to read it from a file, but it is very slow, can someone help shorten the time?

Here is my code to read it very slowly:

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

public class FileInput {

  public static void main(String[] args) {

    Scanner scan1 = new Scanner(System.in);
    String filename = scan1.nextLine();

    File file = new File(filename);
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    DataInputStream dis = null;

    try {
          fis = new FileInputStream(file);

      bis = new BufferedInputStream(fis);
      dis = new DataInputStream(bis);

      while (dis.available() != 0) {

        System.out.println(dis.readLine());
      }

      fis.close();
      bis.close();
      dis.close();

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
+3
source share
3 answers

Do not use DataInputStreamto read lines from a file. Instead, use BufferedReaderas in:

fis = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
while ((String line = reader.readLine()) != null) {
  System.out.println(line);
}

The javadoc DataInputStream.readLinedoesn’t indicate that you are not using this method. (he is out of date)

, , Scanner . , , Scanner :

Scanner fileScanner = new Scanner(file, "UTF-8").useDelimiter(" +| *(?=\\n)|(?<=\\n) *");
while (fileScanner.hasNext()) {
  List<Integer> numbersOnLine = new ArrayList<Integer>();
  while (fileScanner.hasNextInt()) {
    numbersOnLine.add(fileScanner.nextInt());
  }
  processLineOfNumbers(numbersOnLine);
  if (fileScanner.hasNext()) {
    fileScanner.next(); // clear the newline
  }
}

, Scanner.

+5

, println . . Java-... C/++ , .

+1
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;


public class file {
public static void main(String[] args){
    Scanner keyboard = new Scanner(System.in);
    String fname = "";
    System.out.print("File Name: ");
    fname = keyboard.next();

    try{
        Scanner file1 = new Scanner(new FileReader(fname));
        System.out.println("File Open Successful");
        int length = file1.nextInt();
        String[] content = new String[length];
        for (int i=0;i<length;i++){
            content[i] = file1.next();
        }
        for (int i=0;i<length;i++){
            System.out.println("["+i+"] "+content[i]);
        }
        System.out.println("End of file.");

    } catch (FileNotFoundException e){
        System.out.println("File Not Found!");
    }   


}

}

0
source

Source: https://habr.com/ru/post/1766587/


All Articles