In: Computer Science
1.
Write a public Java class called WriteFile which opens an empty file called letters.dat. This program will read a String array called letters and write each word onto a new line in the file. The method should include an appropriate throws clause and should be defined within a class called TFEditor.
The string should contain the following words:
{“how”, “now”, “brown”, “cow”}
Here are the 2 classes you will be needing - TextFileEditior.java and WriteFile.java. You need to run the WriteFile.java. ========================================================================== import java.io.File; import java.io.FileWriter; import java.io.IOException; public class TextFileEditor { final private String fileName; public TextFileEditor() { this.fileName = "letters.dat"; } public void writeToFile(String[] words) throws IOException { FileWriter writer = new FileWriter(new File(fileName)); if (words == null || words.length == 0) throw new IllegalArgumentException("String array empty or null."); for (String word : words) { writer.write(word + "\r\n"); } writer.flush(); writer.close(); System.out.println("File: " + fileName + " updated sucessfully."); } }
================================================================
import java.io.IOException;
public class WriteFile { public static void main(String[] args) { String words[] = {"how", "now", "brown", "cow"}; TextFileEditor editor = new TextFileEditor(); try { editor.writeToFile(words); } catch (IOException e) { System.out.println("Error: File not found."); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } }
================================================================