Last active
May 30, 2019 17:09
-
-
Save eniallator/2e49c8b63464ccaadb142250618ce61d to your computer and use it in GitHub Desktop.
File IO using Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.nio.file.Files; | |
import java.nio.file.Paths; | |
import java.util.Scanner; | |
public class FileIO { | |
public void printLines(String fileName) throws Exception { | |
File file = new File(fileName); | |
Scanner sc = new Scanner(file); | |
while (sc.hasNextLine()) { | |
System.out.println(sc.nextLine()); | |
} | |
} | |
public void alternativePrintLines(String fileName) throws Exception { | |
String contents = new String(Files.readAllBytes(Paths.get(fileName))); | |
for (String line : contents.split("\n")) { | |
System.out.println(line); | |
} | |
} | |
public void writeContents(String fileName, String contents) throws Exception { | |
FileWriter writer = new FileWriter(fileName); | |
writer.write(contents); | |
writer.close(); | |
} | |
public static void main(String[] args) { | |
FileIO fIO = new FileIO(); | |
try { | |
fIO.alternativePrintLines("PATH TO FILE"); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment