Responsive Ad Area

Share This Post

Blog Role / Featured Tutorials / Java

Reading and Writing files using Java

Reading and Writing files using Java

This is the first post in this trail about Java File IO.
Next post in this trail is Reading and Writing Property Files using Java

I'm going to be working a lot of new content for Arksoft.org this year. Starting with Files. My content will mainly be alternate examples that I happen to be interested in working on. One of the first things you need to learn to do with any programming language is read and write to files. So you want to do something interesting, chances are you need to store some info for later use and retrieval. Java has a package called java.io and java.nio which handle file io and stream io. There are two basic types of files I guess you might say that we can read or write to. Binary files or text files. And a text file technically is a binary file that contains at least ASCII text. Or the more modern Unicode text.  For starters we simply want to read and write something to a simple ASCII text file.

Reading a Text File


import java.io.*;

public class AFileReader {
 private static String aFileName = "textfile1.txt";
 public static void main(String[] args) {
  try (BufferedReader br = new BufferedReader(new FileReader(aFileName))) {
   String aLine;
    while ((aLine = br.readLine()) != null) {
     System.out.println(aLine);
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
}

Writing to a Text File


import java.io.*;

public class AFileWriter {
 private static String aFileName = "textfile1.txt";
  public static void main(String[] args) {
   try (BufferedWriter bw = new BufferedWriter(new FileWriter(aFileName))) {
    String aString = "The quick brown fox jumped over the fence.\n";
    bw.write(aString);
   } catch (IOException e) {
    e.printStackTrace();
   }
 }
}

Appending to a File

import java.io.*;
public class AFileAppender {
 private static String aFileName = "textfile1.txt";
  public static void main(String[] args) {
   try (BufferedWriter bw = new BufferedWriter(new FileWriter(aFileName,true))) {
    String aString = "The quick brown fox jumped over the fence.\n";
    bw.write(aString);
   } catch (IOException e) {
    e.printStackTrace();
   }
 }
}

This is the first post in this trail about Java File IO.
Next post in this trail is Reading and Writing Property Files using Java

 

Share This Post

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>