In: Computer Science
Write a java program:
Write a program that creates a text file. Write to the file three lines each line having a person's name. In the same program Append to the file one line of 'Kean University'. In the same program then Read the file and print the four lines without lines between.
The following code will do the job required. THUMBS UP if it helps :)
Main.java
import java.io.*;
public class Main {
public static void appendStrToFile(String fileName, String
str)
{
try {
BufferedWriter out = new BufferedWriter(
new FileWriter(fileName, true));
out.write(str);
out.close();
}
catch (IOException e) {
System.out.println("exception occoured" + e);
}
}
public static void main(String[] args)
throws Exception
{
File mFile = new File("output.txt");
String str = "Kean University";
try {
BufferedWriter out = new BufferedWriter(
new FileWriter(mFile));
out.write("Alice\n");
out.write("Danny\n");
out.write("Diana\n");
out.close();
// Changing Text.
BufferedReader in = new BufferedReader(new
FileReader("output.txt"));
String mystring;
while ((mystring = in.readLine()) != null) {
str = str + "\n" + mystring;
}
mFile.delete();
}
catch (IOException e) {
System.out.println("Exception Occurred" + e);
}
appendStrToFile("output.txt", str);
//printing
BufferedReader in = new BufferedReader(new
FileReader("output.txt"));
String stringFile;
while ((stringFile = in.readLine()) != null) {
System.out.println(stringFile);
}
}
}
OUTPUT
1) output.txt before running append.
2)After Running Code.
Hope it helped :)