Switch to full style
General Java code examples
Post a reply

File write read

Fri Jan 02, 2009 11:25 pm

This a simple method to read and write from/in file. hope it helps

Code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileManipulator {
    private File file;
    
    
// constructor
    public FileManipulator(File file) {
        this.file = file;
    }

    public FileManipulator(String filePath) {
        file = new File(filePath);
    }
    
    
// reading method 
    public String ReadFromFile() {
        String str = "", tempStr = "";
        BufferedReader br;
        try {
            br = new BufferedReader(new FileReader(this.file));
            while ((tempStr = br.readLine()) != null)
                str += tempStr + "\n";
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return str
;
        
    
}
    //writing method 
    public void WriteInFile(String content) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            bw.write(content);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        FileManipulator fm = new FileManipulator("input.txt");
        String content = fm.ReadFromFile();
        System.out.println(content);
        fm.file = new File("output.txt");
        fm.WriteInFile(content);
    }

}
 



Attachments
FileManipulator.java
(1.31 KiB) Downloaded 1071 times

Re: File write read

Sat Jan 03, 2009 12:13 am

Thank you so much :) .For you share .
I moved your topic to java examples :).

Have a nice time .

Post a reply
  Related Posts  to : File write read
 Read and write CSV file     -  
 Read and Write to file using ASP     -  
 How to read and write to CSV file from python     -  
 Write and Read to File In Java Example     -  
 Write to file using php     -  
 Write Vector list to File     -  
 read from file in C++     -  
 Read csv file     -  
 File read by char     -  
 read file in matlab     -  

Topic Tags

Java Files and I/O