Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 1st, 2012  |  syntax: None  |  size: 1.38 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Creating a file and writing to it
  2. package InputOutput;
  3.  
  4. import java.io.*;
  5.  
  6. public class CharacterFileReaderAndFileWriter{
  7.  
  8. private BufferedReader br = null;
  9. private BufferedWriter bw = null;
  10. private PrintWriter pw = new PrintWriter(System.out, true);
  11.  
  12. public File createFile() throws IOException{
  13.     File f = new File("test.txt");
  14.     return f;
  15. }
  16.  
  17. public void writeToFile() throws IOException{
  18.     try{
  19.         bw = new BufferedWriter(new FileWriter(createFile()));
  20.     }
  21.     catch(FileNotFoundException ex){
  22.         ex.printStackTrace();
  23.     }
  24.  
  25.     //take input from the console (user)
  26.     br = new BufferedReader(new InputStreamReader(System.in));
  27.     String s;
  28.  
  29.     pw.println("Please enter something");
  30.     pw.println("To stop the program, enter 'stop'");
  31.  
  32.     do{
  33.         s = br.readLine();
  34.         if(s.compareTo("stop")==0)
  35.             break;
  36.         s+= "rn";//adding an new line to the string s        
  37.         bw.write(s);            
  38.     }
  39.     while(s.compareTo("stop")!=0);
  40.  
  41.     br.close();
  42.     bw.close();
  43.  
  44. }
  45.  
  46. public static void main(String[] args) throws IOException{
  47.  
  48.     CharacterFileReaderAndFileWriter cfr = new CharacterFileReaderAndFileWriter();
  49.     cfr.writeToFile();
  50. }
  51.        
  52. if(s.compareTo("stop")==0)
  53.        
  54. if ("stop".equalsIgnoreCase(s))
  55.        
  56. s+= "rn";//adding an new line to the string s        
  57.     bw.write(s);
  58.        
  59. bw.write(System.getProperty("line.separator"));        
  60.     bw.write(s);