We Recommend

Java How to Program Java How to Program
Takes a new tools-based approach to Web application development that uses Netbeans 5.5 and Java Studio Creator 2 to create and consume Web Services. Features new AJAX-enabled, Web applications built with JavaServer Faces (JSF), Java Studio Creator 2 and the Java Blueprints AJAX Components. Includes new topics throughout, such as JDBC 4, SwingWorker for multithreaded GUIs, GroupLayout, Java Desktop Integration Components (JDIC), and much more.


Posted By

The_Englishman on 05/02/07


Tagged

file io read write readwrite


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

The_Englishman


ReadWrite


Published in: Java 


  1. /**
  2.  * Class to read inputs from the command line and write to files.
  3.  */
  4. class ReadWrite
  5. {
  6. /**
  7. * Reads the input from command line and returns it as a string.
  8. */
  9. public String readStr()
  10. {
  11. String str = "";
  12. try
  13. {
  14. str = in.readLine();
  15. }
  16. catch (IOException e)
  17. {
  18. System.out.println(e);
  19.  
  20. }
  21. return str;
  22. }
  23.  
  24. /**
  25. * Reads the specified file.
  26. */
  27. public String readFile(String file)
  28. {
  29. String data = "";
  30. try
  31. {
  32. String str;
  33. while ((str = in.readLine()) != null)
  34. {
  35. sb.append((String) str);
  36. }
  37. data = sb.toString();
  38. in.close();
  39. }
  40. catch (IOException e)
  41. {
  42. System.out.println(e);
  43. }
  44.  
  45. return data;
  46. }
  47.  
  48. /**
  49. * Writes the specified string to the file specified.
  50. * Will overwrite file if same name is specified as an existing file.
  51. */
  52. public void writeFile(String fileName, String contents)
  53. {
  54. try
  55. {
  56. BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
  57. out.write(contents.trim());
  58. out.close();
  59. }
  60. catch (IOException e)
  61. {
  62. System.out.println(e);
  63. }
  64. System.out.println("The File has been written.");
  65. }
  66. }

Report this snippet 

You need to login to post a comment.