Responsive Ad Area
Home » Blog » File IO: Reading and Writing files using Java

Share This Post

Blog Role / Featured Tutorials / Java / Tutorial

File IO: Reading and Writing files using Java

File IO: Reading and Writing files using Java

Reading and Writing files line by line with Java

I'm going to be working a lot of new content for Software Developer Zone 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.

Working with Java and Files Tutorial Trail
 Delimited Files

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();
   }
 }
}

 

 

 

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>