If you think that this site is helpful, please recommend your friends to visit our site.
How to read file, append file, and write file in java?
The following is the code to retrieve data from file, append data to file, and save data to file in java:
-------------------------------------------------------------------------------- package test; /** * Title: test * Description: * Copyright: Copyright (c) 1994-2011. www.edusoftmax.com * Company: * @author * @version 1.0 */ import java.io.*; import java.util.*; public class test { public static void main (String args[]) { FileOutputStream out; // declare a file output object //FileInputStream in; DataInputStream in; // = new DataInputStream(fstream); PrintStream p; // declare a print stream object try { // Create a new file output stream out = new FileOutputStream("c:\\test.txt"); // Connect print stream to the output stream p = new PrintStream( out ); p.println ("linda,smith"); p.close(); // file append FileWriter myWriter = new FileWriter("c:\\test.txt", true); myWriter.write("\n" + "String to be appended." ); myWriter.close(); FileInputStream fstream = new FileInputStream("c:\\test.txt"); in = new DataInputStream(fstream); String line = null; int wordCount = 0; while ((line = in.readLine()) != null) { //use StringTokenizer to read comma delimited file or string StringTokenizer st = new StringTokenizer(line, ","); while (st.hasMoreTokens()) { System.out.println("The first character of word " + (++wordCount) + " is: " + st.nextToken().substring(0,1)); } } in.close(); } catch (Exception e) { System.err.println ("Error writing to file"); } } } -------------------------------------------------------------------------------- For reading file character by character, you can use the following code: -------------------------------------------------------------------------------- import java.io.*; public class ReadFileChar { public static void main(String[] args) throws IOException { BufferedReader in = null; int ich; char ch; int char_count=0; // read character from test file in = new BufferedReader( new FileReader( "c:\\test.txt" )); while ( (ich=in.read()) != -1) { // extract character ch = (char) ich; char_count++; System.out.println( "count = " + char_count + " int = " + ich + " char = " + ch ); } in.close(); } }
No comments:
Post a Comment