Skip to content

Commit

Permalink
Added FileIO in Java
Browse files Browse the repository at this point in the history
  • Loading branch information
raj808569 committed Oct 13, 2019
1 parent 65ec0be commit e5a884b
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
65 changes: 65 additions & 0 deletions archive/j/java/FileIo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileIo {

public static void main(String[] args) {

// create a new file output.txt
File file =new File("output.txt");

//method to open a file and add contents
writeToFile(file);
//method to open the file and print its content line by line
readFile(file);

}

public static void readFile(File file) {

try {

BufferedReader buffer=new BufferedReader(new FileReader(file));
try {
String nextLine=buffer.readLine();// read the file one line at a time
while(nextLine!=null) {
//display the line on the screen
System.out.println(nextLine);
nextLine=buffer.readLine(); // read the next line to print
}
buffer.close();
} catch (IOException e) {

System.out.println("Error occurred while reading the file");
}

} catch (FileNotFoundException e) {

System.out.println("Error occurred while opening the file!");
}

}

public static void writeToFile(File file) {

String content = "We wish you a Merry Christmas\n" +
"We wish you a Merry Christmas\n" +
"We wish you a Merry Christmas\n" +
"And a happy New Year.";
try {
FileWriter writer = new FileWriter(file);
writer.write(content);
writer.close(); // closes the file
} catch (IOException e) {

System.out.println("Error occurred while writing contents to file!");
}

}

}

2 changes: 1 addition & 1 deletion archive/j/java/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Welcome to Sample Programs in Java!
- [Hello World in Java](https://therenegadecoder.com/code/hello-world-in-java/)
- [Reverse a String in Java](https://therenegadecoder.com/code/java/reverse-a-string-in-java/)
- [Capitalize a String in Java](https://github.com/TheRenegadeCoder/sample-programs/issues/1366)

- [File IO in Java](https://sample-programs.therenegadecoder.com/projects/file-io/)
## Fun Facts

- Debut: 1995
Expand Down

0 comments on commit e5a884b

Please sign in to comment.