In: Computer Science
Then try:
***
ADDITIONAL NOTES IN CASE YOU ARE HAVING I/O TROUBLES:
//Writing from your Source Code to an External .txt File:
PrintWriter outputFile = new
PrintWriter("names.txt");
outputFile.println("Mike");
outputFile.close();
*************
//Appending from your Source Code to an External .txt File:
FileWriter fileWrite = new FileWriter("names.txt", true);
PrintWriter outWrite = new PrintWriter(fileWrite);
outWrite.println("John");
outWrite.close();
*************
//Reading from an external .txt File into your Source Code:
File myFile = new File("Customers.txt");
Scanner inputFile = new Scanner(myFile);
String str = inputFile.nextLine();
inputFile.close();
/**********************FileIO.java***************************/
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class FileIO {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
char option = ' ';
System.out.print("Enter File name:
");
String fileName =
scanner.nextLine();
do {
readFromFile(fileName);
System.out.println("Enter the name you want to write: ");
String name =
scanner.nextLine();
writeToFile(fileName, name);
System.out.print("Do you want to try again(Y/N): ");
option =
scanner.nextLine().toUpperCase().charAt(0);
} while (option != 'N');
scanner.close();
}
private static void writeToFile(String string,
String name) {
try {
FileWriter
fileWrite = new FileWriter(string, true);
PrintWriter
outWrite = new PrintWriter(fileWrite);
outWrite.println(name);
outWrite.close();
} catch (Exception e) {
System.out.println("File not found!");
}
}
private static void readFromFile(String filename)
{
try {
File myFile =
new File(filename);
Scanner
inputFile = new Scanner(myFile);
while
(inputFile.hasNextLine()) {
String str = inputFile.nextLine();
System.out.println(str);
}
inputFile.close();
} catch (Exception e) {
System.out.println("File not found!");
}
}
}
/*******************output*********************/
Enter File name: names.txt
Mike
John
Enter the name you want to write:
JKS
Do you want to try again(Y/N): Y
Mike
John
JKS
Enter the name you want to write:
MS Dhoni
Do you want to try again(Y/N): Y
Mike
John
JKS
MS Dhoni
Enter the name you want to write:
Jadeja
Do you want to try again(Y/N): N
Please let me know if you have any doubt or modify the answer, Thanks :)