Home Answers Viewqa Java-Beginners How to format text file?

 
 


manjiri
How to format text file?
1 Answer(s)      4 years and 5 months ago
Posted in : Java Beginners

View Answers

December 17, 2008 at 4:30 AM


Hi friend,


I am sending running code. I hope that this code will help you.



import java.io.*;

public class ReadWriteTextFile {

static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();

try {

BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop

while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}

return contents.toString();
}


static public void setContents(File aFile, String aContents)
throws FileNotFoundException, IOException {
if (aFile == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!aFile.exists()) {
throw new FileNotFoundException ("File does not exist: " + aFile);
}
if (!aFile.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) {
throw new IllegalArgumentException("File cannot be written: " + aFile);
}

//use buffering
Writer output = new BufferedWriter(new FileWriter(aFile));
try {
//FileWriter always assumes default encoding is OK!
output.write( aContents );
}
finally {
output.close();
}
}

public static void main(String args[]) throws IOException {
File testFile = new File("/home/vinod/amarexamples/anju.txt");
System.out.println("Original file contents: " + getContents(testFile));
setContents(testFile, "The content of this file has been overwritten...");
System.out.println("New file contents: " + getContents(testFile));
}
}

-----------------------------------------

Visit for more information.

http://www.roseindia.net/java/example/java/io/java-read-file-line-by-line.shtml

Thanks.









Related Pages:

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.