Skip to content

Instantly share code, notes, and snippets.

@maf946
Last active December 11, 2023 15:45
Show Gist options
  • Save maf946/0926d18051b7968a24d78b216efae011 to your computer and use it in GitHub Desktop.
Save maf946/0926d18051b7968a24d78b216efae011 to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.Scanner;
public class Main
{
public static void writeFile()
{
PrintWriter out = null;
try
{
out = new PrintWriter("writeFile.txt");
out.println("Line 1\nLine 2\nLine 3");
}
catch (FileNotFoundException fne)
{
System.out.println(fne.getMessage());
}
finally
{
if (out != null)
{
out.close();
}
}
}
public static void readFile()
{
File fileToRead = new File("readFile.txt");
Scanner readScanner = null;
try
{
readScanner = new Scanner(fileToRead);
while (readScanner.hasNextLine())
{
String newLine = readScanner.nextLine();
System.out.println(newLine);
}
}
catch (FileNotFoundException fne)
{
System.out.println(fne.getMessage());
}
finally
{
if (readScanner != null)
{
readScanner.close();
}
}
}
public static void main(String[] args)
{
writeFile();
readFile();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment