Advertisement
Guest User

Untitled

a guest
Jan 25th, 2016
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.03 KB | None | 0 0
  1. /*SentenceRecorder.java
  2. takes a sentence or word as input and saves it on text file. Every new word/sentence is appended at the end of the file
  3. */
  4. import javax.swing.event.*;
  5. import javax.swing.JFrame;
  6. import javax.swing.JTextField;
  7. import javax.swing.JLabel;
  8. import javax.swing.JButton;
  9. import javax.swing.JTextArea;
  10. import javax.swing.JScrollPane;
  11. import java.awt.GridBagLayout;
  12. import java.awt.GridBagConstraints;
  13. import static java.awt.GridBagConstraints.*;
  14. import java.awt.Insets;
  15. import java.awt.event.ActionEvent;
  16. import java.awt.event.ActionListener;
  17. import java.awt.Dimension;
  18. import java.io.File;
  19.  
  20.  
  21. import java.nio.file.*;//for readAllLines()
  22. import java.nio.file.Paths;//used to get the path of the file
  23. import java.util.ArrayList;//to work with the array list to save the sentences in an ArrayList
  24. import java.util.List;
  25. import java.util.Collection;
  26. import java.nio.charset.Charset;
  27. import java.nio.charset.StandardCharsets;
  28.  
  29. import java.util.Scanner;
  30. import java.io.FileWriter;
  31. import java.lang.SecurityException;//if no permission to write to file
  32. import java.io.FileNotFoundException;//if the file can't be created
  33. import java.io.IOException;
  34. import java.util.Properties;//to get working directory
  35. import java.io.BufferedWriter;
  36.  
  37. public class SentenceRecorder extends JFrame{
  38. private JLabel instructions;
  39. private JButton submit;
  40. private JButton search;
  41. private GridBagLayout gbLayout;
  42. private JButton clear;
  43. private JTextArea input;
  44. private JTextArea searchResults;//displays the search results
  45. private String stringInput;
  46. private List< String > allSentences = new ArrayList< String >();//stores all the sentences in the file
  47. private String filePath;
  48. private String fileName;
  49. private JTextField searchCriterium;
  50. private File file;
  51. private BufferedWriter fileWriter;
  52. private String workingDir;
  53. private String separator;
  54. private Scanner scannerInput;//to input data into the file
  55. private Scanner scannerOutput;//to output data from the file
  56. private final static Charset ENCODING = StandardCharsets.UTF_8;
  57. public SentenceRecorder(){
  58. super("List of sentences to remember");
  59. searchCriterium = new JTextField();
  60. separator = System.getProperty("line.separator");//getting the system-dependent separator
  61. workingDir = System.getProperty("user.dir");
  62. instructions = new JLabel("Enter your sentence.");
  63. input = new JTextArea(10,12);//holds the text input
  64. searchResults = new JTextArea(10,12);
  65. submit = new JButton("Submit");//submit button
  66. //search = new JButton("Search");//search button
  67. clear = new JButton("Clear");//clear button
  68. stringInput = "";//initialize string to empty
  69. gbLayout = new GridBagLayout();
  70. //System.out.println("workingDir is " + workingDir);
  71. //input = new Scanner(System.in);
  72. fileName = "sample.txt";
  73. /* filePath = workingDir + "\\sample.txt";
  74. file = new File(filePath); */
  75. file = new File(workingDir, fileName);
  76. allSentences = getSentenceList(fileName);//copying content of file in arrayList
  77. printSentenceArray(allSentences);
  78. //getSentenceContaining("sentence");
  79. setLayout(gbLayout);//set layout of jframe
  80. add(instructions, new GridBagConstraints(0,0,2,1,0,0,CENTER,HORIZONTAL, new Insets(10,15,10,15),0,0));
  81. add(new JScrollPane(input), new GridBagConstraints(0,1,2,1,0.5,0.5,CENTER,BOTH, new Insets(10,15,10,15),10,10));
  82. add(submit, new GridBagConstraints(0,2,1,1,1.0,1.0,CENTER,HORIZONTAL,new Insets(10,15,10,15),1,1));
  83. add(clear, new GridBagConstraints(1,2,1,1,1.0,1.0,CENTER,HORIZONTAL,new Insets(10,15,10,15),1,1));
  84. add(searchCriterium, new GridBagConstraints(0,3,1,1,1.0,1.0,CENTER,HORIZONTAL,new Insets(10,15,10,15),1,1));
  85. add(new JScrollPane(searchResults), new GridBagConstraints(0,4,2,1,0.5,0.5,CENTER,BOTH, new Insets(10,15,10,15),10,10));
  86. //System.out.printf("Enter your sentence or end of file - ctrl+z or Enter+ctrl+d\n");
  87.  
  88.  
  89. searchCriterium.getDocument().addDocumentListener(new DocumentListener(){
  90. public void changedUpdate(DocumentEvent e){
  91. //System.out.println("changedUpdate");
  92. }
  93. public void removeUpdate(DocumentEvent e){
  94. //System.out.println("removeUpdate");
  95. //searchResults.setText(getSentenceContaining(getKeyword()));
  96. getMatchedSentence(getSentenceContaining(getKeyword()));
  97. }
  98. public void insertUpdate(DocumentEvent e){
  99. //System.out.println("insertUpdate");
  100. getMatchedSentence(getSentenceContaining(getKeyword()));
  101. //searchResults.setText(getSentenceContaining(getKeyword()));
  102. }
  103. });
  104.  
  105. ProcessButtonHandling handler1 = new ProcessButtonHandling();
  106. ClearButtonHandling handler2 = new ClearButtonHandling();
  107. //SearchButtonHandling handler3 = new SearchButtonHandling();
  108. submit.addActionListener(handler1);
  109. clear.addActionListener(handler2);
  110. }//end of constructor
  111. //inner class for event handlings
  112. private class ProcessButtonHandling implements ActionListener{
  113. public void actionPerformed(ActionEvent event){
  114. stringInput = input.getText();//copy text from textArea to string
  115. scannerInput = new Scanner(stringInput);
  116. try{
  117. fileWriter = new BufferedWriter( new FileWriter(file,true));
  118. }
  119. catch(SecurityException securityException){//if you don't have write access
  120. System.err.println("You don't have write access to this file");
  121. System.exit(1);
  122. }
  123. catch(FileNotFoundException fileNotFoundException){
  124. System.err.println("Error opening or creating the file");
  125. System.exit(1);
  126. }
  127. catch(IOException ioexception){
  128. System.err.println("General Error with IO");
  129. System.exit(1);
  130. }
  131. while(scannerInput.hasNext()){
  132. stringInput = scannerInput.nextLine();
  133. try{
  134. fileWriter.append(stringInput + separator);
  135. }
  136. catch(IOException ioexception){
  137. System.err.println("General Error with IO");
  138. ioexception.printStackTrace();
  139. System.exit(1);
  140. }
  141. //System.out.printf("Enter your sentence or end of file - ctrl+z or Enter+ctrl+d\n");
  142. }
  143. CloseFile();
  144. Clear();
  145. }//end of actionPerformed
  146.  
  147. }//end of inner class
  148. private class ClearButtonHandling implements ActionListener{
  149. public void actionPerformed(ActionEvent event){
  150. Clear();
  151. }//end of actionPerformed
  152. }
  153. /* private class SearchButtonHandling implements ActionListener{
  154. public void actionPerformed(ActionEvent event){
  155. //return the matched sentences
  156. //copy them into the textArea
  157. }
  158. } */
  159. private void Clear(){
  160. stringInput = "";
  161. input.setText("");
  162. CloseFile();
  163. }
  164. public void CloseFile(){
  165. try{
  166. fileWriter.close();
  167. }
  168. catch(IOException ioexception){
  169. System.err.println("General Error with IO");
  170. ioexception.printStackTrace();
  171. System.exit(1);
  172. }
  173. }//closeFile
  174. public List<String> getSentenceList(String theFileName){//save file text into array
  175. Path path = Paths.get(theFileName);
  176.  
  177. if(!(Files.isReadable(path))){
  178. System.out.println("The file is empty. You need to save something in it first.");//to be printed in the textArea
  179. return null;
  180. }
  181. try{
  182. return Files.readAllLines(path, ENCODING);
  183. }
  184. catch(IOException ioexception){
  185. System.err.println("General Error with IO");
  186. ioexception.printStackTrace();
  187. System.exit(1);
  188. }
  189. return null;
  190. }
  191. public void printSentenceArray(List< String > toPrint){
  192. if((toPrint == null)||(toPrint.size() == 0)){//to avoid NPE
  193. System.out.println("List is empty: ");
  194. return;
  195. }
  196. System.out.println("Array contains " + toPrint.size() + " sentences:");
  197. for(String s: toPrint){
  198. //System.out.printf("%s", toPrint.get(count));
  199. System.out.println(s);
  200. }
  201.  
  202. }
  203. public List<String> getSentenceContaining(String keyword){// search for keyword and return the whole string/s
  204. if(keyword.length() > 3){
  205. System.out.printf("\n\nKeyword is %s. Sentence(s) containing the keyword:\n", keyword);
  206. List< String > matchedSentences = new ArrayList< String >();//stores all the matched sentences in the file
  207. //int instanceFound = 0;
  208. for(String toFind : allSentences){
  209. if(toFind.contains(keyword)){
  210. //instanceFound++;
  211. matchedSentences.add(toFind);//add the found sentences to the List
  212. //System.out.println(toFind);
  213. }
  214. }
  215. /* if(instanceFound == 0){//no matches
  216. System.out.println("None found matching the keyword");
  217. }
  218. else if(instanceFound > 0){
  219. printSentenceArray(matchedSentences);
  220. } */
  221. if(matchedSentences.size() == 0){//no matches
  222. System.out.println("None found matching the keyword");
  223. }
  224. else if(matchedSentences.size() > 0){
  225. printSentenceArray(matchedSentences);
  226. }
  227. return matchedSentences;
  228. }
  229. else{//necessary, otherwise compiler complains no return statement
  230. return null;
  231. }
  232. }
  233.  
  234. public String getKeyword(){//get keyword from input field
  235. String text = searchCriterium.getText();
  236. return text;
  237. }
  238. public void getMatchedSentence(List< String > matchedSent){//loops thru matched sentences
  239. for(String theSentence : matchedSent){
  240. searchResults.append(theSentence + separator);
  241. }
  242.  
  243. }
  244. }//end of SentenceRecorder
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement