AlphaCharDocument.java 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package rocks.zipcode;
  2. import java.io.*;
  3. import java.util.Scanner;
  4. /**
  5. * @author leon on 16/11/2018.
  6. */
  7. public class AlphaCharDocument extends Document {
  8. //private String fileName;
  9. private File file;
  10. //private FileWriter fw = new FileWriter(file);
  11. public AlphaCharDocument(String fileName) throws IOException {
  12. super(fileName);
  13. this.file = new File(fileName);
  14. // this.fileName = fileName;
  15. // fw = new FileWriter(file);
  16. }
  17. @Override
  18. public void write(String contentToBeWritten) {
  19. try {
  20. FileWriter fw = new FileWriter(file);
  21. isAlpha(contentToBeWritten);
  22. fw.write(contentToBeWritten);
  23. fw.close();
  24. } catch (IOException ex) {
  25. ex.printStackTrace();
  26. }
  27. }
  28. public String read() throws FileNotFoundException {
  29. try {
  30. Scanner scanner = new Scanner(file);
  31. StringBuilder sb = new StringBuilder();
  32. while(scanner.hasNextLine()){
  33. sb.append(scanner.nextLine());
  34. }
  35. String content = sb.toString();
  36. return content;
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. }
  40. return null;
  41. }
  42. private void isAlpha(String s) throws IOException {
  43. if(!s.matches("[a-zA-Z\\s]*"))
  44. throw new IllegalArgumentException();
  45. }
  46. }