Tuesday, March 11, 2014

Java : Text Reader and Text Writer into other file

 Text Reader and Text Writer into other file

Function to Write Data from a Text File : -

    // sData = Contains the data to be written  (String buffer type)
    //sPath = Path of the new file which is created and sData is written into

    public void Write_text(StringBuffer sData ,String sPath)
    {
        BufferedWriter writer = null;
        try {
//            String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
            File newFile = new File(sPath);
            writer = new BufferedWriter(new FileWriter(newFile));
            writer.append(sData);//write(sData);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (Exception e) {
            }
        }
       
    }

   
   

Function to Read Data from a Text File : -

    // sPath contains the path of the file to be read
    // ex : "C:\\Users\\deepakj\\Desktop\\report.txt"
   
    public StringBuffer Read_text(String sPath)
    {

StringBuffer Reporter = new StringBuffer();
         try { 
                File file = new File(sPath);//"C:\\Users\\deepakj\\Desktop\\report.txt");  // Path of the html file
                FileReader fr = new FileReader(file);  
                BufferedReader br = new BufferedReader(fr);                                                  
                String data = null;

                while((data = br.readLine()) != null)    
                {    
                    Reporter.append(data+"\n"); 
                }        
               
                System.out.print(Reporter);
            } catch(IOException e)
            { 
                System.out.println("bad !"); 
            }        
             return Reporter;
    }

No comments:

Post a Comment