Importing Data in Java
Anthony Markham
VP Quant Developer
InputStream/OutputStream)Reader/Writer)
InputStream (reading), OutputStream (writing)FileInputStream, FileOutputStreamread() returns bytes, write() outputs bytes
try (FileInputStream fis = new FileInputStream("data.bin")) {byte[] buffer = new byte[1024]; int bytesRead;while ((bytesRead = fis.read(buffer)) != -1) { // Process bytes in bufferSystem.out.println("Read " + bytesRead + " bytes"); }} catch (Exception e) { System.err.println("Error: " + e.getMessage()); }
Reader (reading text), Writer (writing text)FileReader, FileWriter, BufferedReader, BufferedWriterreadLine() reads a full line of text
try (BufferedReader reader = new BufferedReader(new FileReader("data.csv"))) { String line;while ((line = reader.readLine()) != null) { // Process each line System.out.println(line); }} catch (Exception e) { System.err.println("Error: " + e.getMessage()); }
BufferedInputStream and BufferedOutputStreamBufferedReader, BufferedWriterreadLine()try (BufferedReader reader = new BufferedReader(new FileReader("data.csv"))) { // Header processing String header = reader.readLine(); System.out.println("Header: " + header);// Efficient data reading String line; int count = 0; while ((line = reader.readLine()) != null) { count++; } System.out.println("Read " + count + " data rows"); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); }
FileInputStream -> InputStreamReader -> BufferedReaderimport java.nio.charset.StandardCharsets;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("data.csv"),StandardCharsets.UTF_8 ))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line);} } catch (Exception e) { System.err.println("Error: " + e.getMessage()); }
IOException, FileNotFoundExceptionimport java.util.ArrayList;
import java.util.List;
public static List<String> readLines(String filePath) throws IOException {List<String> lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { String line; while ((line = reader.readLine()) != null) { lines.add(line); } } // Stream automatically closed here return lines;}
Importing Data in Java