Skip to content

Instantly share code, notes, and snippets.

@eniallator
Last active May 30, 2019 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eniallator/2e49c8b63464ccaadb142250618ce61d to your computer and use it in GitHub Desktop.
Save eniallator/2e49c8b63464ccaadb142250618ce61d to your computer and use it in GitHub Desktop.
File IO using Java
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