Thursday, July 26, 2012

Reading and writing text files in Java

Introduction

Just simple log

Program fragment

Read file

where the "data.txt" is under project root

            File srcFile = new File( "data.txt" );
            BufferedReader br =
                new BufferedReader(new InputStreamReader(
                    new FileInputStream(srcFile), "UTF-8"));
            while( br.ready() ) {
                System.out.println(br.readLine());
            }
            br.close();


Write text to file

            File destFile = new File("dest.txt");
            if (!destFile.exists()) {
                destFile.createNewFile();
            }
            BufferedWriter bw =
                new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(destFile), "UTF-8"));
            bw.write("test\n");
            bw.write("test test");
            bw.flush();
            bw.close();

Reference
http://docs.oracle.com/javase/tutorial/i18n/text/stream.html

No comments:

Post a Comment