import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { String[] fileContents = getFileContents("nums.txt"); for(int i = 0; i < fileContents.length; i++) { System.out.println(fileContents[i]); } writeArrayToFile("output.txt", fileContents); } // main // reads fileName and returns the contents as String array // with each line of the file as an element of the array public static String[] getFileContents(String fileName){ String [] content = null; try { // Read the lines from the file and collect them into a list List lines = Files.lines(Paths.get(fileName)) .collect(Collectors.toList()); // copy the lines from the list into a 1D array content = lines.toArray(new String[0]); } catch (IOException e) { System.out.println("File Read Error"); e.printStackTrace(); } return content; } // getFileContents // writes the array a to fileName, one array element per line in the file public static void writeArrayToFile(String fileName, String [] a) { // this is called a try-with-resources // it automatically closes the resource when // the program is done with it try (FileWriter writer = new FileWriter(fileName)) { // Write each line followed by a newline character for (String line : a) { writer.write(line + "\n"); } } catch (IOException e) { System.out.println("File Write Error"); e.printStackTrace(); } } // writeArrayToFile } // FileInputOutput