File IO in Java

May 2, 2017
Categorised in: Java Core
Let’s check out the Code
import java.io.FileReader; import java.io.BufferedReader; import java.io.FileWriter; public class FileIO { public static void main( String[] args ){ String src = "example.txt"; //if this file was in a directory. Use forward slash '/' String dst = "exampleCopy.txt"; //Syntax style: try with resources //This will allow Java to call the close() method automatically try( FileReader fr = new FileReader(src); BufferedReader br = new BufferedReader(fr); FileWriter wrtier = new FileWriter(dst); ) { while (true) { String line = br.readLine(); if(line == null) { break; } else { wrtier.write(line + "\n"); } } } catch( Exception e ) { e.printStackTrace(); } } }
Output: exampleCopy.txt gets created and has the same written data as that of example.txt
Notes
- In Java, the forward slash ( / ) is used as directory separator for all Operating Systems.
- The file is read one line at a time.
- If there is no string in the file then it will be null
- We pass in the “\n” because when readLine is called we get only the line and not the line feed along with it. So we need to insert it on our own.
- try with resources syntax was introduced in Java V7.
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.