Monday, January 21, 2013

QnA - Pano ba mag-write and mag-read ng text files?

Ang luma na nitong blog ko and tinigil ko na din ang pagpopost dito kasi nawala na yung mga nagtatanong dati. Then nakareceive uli ako ng question sa comments.  So eto uli tayo para mag-explain. :)

The question is from Maria Jean Cabs.  The way I understand it, gusto nya ng madaling way ng pag output (write) and input (read) ng file.  Anyway, there are several ways para makapag write and read ng files.  Lalo na ngayon sa JDK 7 meron na Paths and Path.  I'm assuming student ka kaya ang ituturo ko na lang ay yung madaling way para madali maintindihan.  Once na maintindihan mo na yun, madali mo na din magegets yung iba pang way.  Anyway, here it is:

Sa pag read ng files:


1  package com.pinoyjavatutorial.qna;
2  import java.io.FileNotFoundException;
3  import java.io.FileReader;
4  import java.util.Scanner;
5  public class IOFilesSample {
6 public static void main(String[] args) {
7 try {
8 Scanner scan = new Scanner(new FileReader("c:\\mau\\file.txt"));
9 while(scan.hasNext()){
10 System.out.println(scan.nextLine());
11 }
12 } catch (FileNotFoundException e) {
13 e.printStackTrace();
14 }
15 }
16 }


Sa lines 7-14 na tayo mag concentrate kasi I'm assuming alam mo na yung the rest.  At line 7, naglagay tayo ng try kasi yung FileReader na object pwedeng wala sya maread.  So kailangan gumamit ng try-catch or magthrow ng Exception.  Pinili ko na lang ang mag try and catch.  

Sa line 8, dalawa ang nangyayari dito.  Meron tayo para sa FileReader, meron din para sa Scanner.  Yung sa FileReader, nagcreate tayo ng new object na FileReader then yung parameter sa loob ay yung path and file ng kung saan yung gusto mong basahin na file.  Sa case natin dito, c:\mau\file.txt ang path and file natin.  Then nag declare tayo ng new object ng Scanner at ang parameter natin na ginamit ay yung FileReader na kakacreate lang din natin.  

At lines 9-11, dito naman ipiprint natin lahat ng laman ng file na nabasa natin.  Hanggang meron pang next line (scan.hasNext()), hindi tayo mag e-exit sa loop na yun.  Jut remember, ang pagbasa ni scan ay line by line.  So sa unang scan.nextLine() ang babasahin nya ay yung unang line ng text file.  Sa second na iteration ang babasahin naman nya ay yung second na iteration etc.   

Here's for writing files:


1 package com.pinoyjavatutorial.qna;
2 import java.io.BufferedWriter;
3 import java.io.FileWriter;
4 import java.io.IOException;
5 public class IOFilesSample {
6 public static void main(String[] args) {
7 try {
8        BufferedWriter out = new BufferedWriter(new FileWriter("c:\\mau\\file2.txt"));
9        out.write("hi and hello from\n");
10        out.write("Pinoy Java Tutorial");
11        out.close();
12    } catch (IOException e) {
13     e.printStackTrace();
14    }
15
16 }
17
18 }

Let's start sa line 8.  Kagaya kanina, dalawa nangyayari dito.  Una, we constructed a FileWriter object and it's pointed at c:\mau directory then ang filename ay file2.txt kaya sya c:\mau\file2.txt.  Then meron tayong BufferedWriter na object.  Kailangan natin to para makapag write ng file.  

Then the rest ng lines ay madali lang.  Line 9 will write "hi and hello from" sa file.  Yung "\n" ay hindi makakasama kasi it means "new line" if you'll remember yung mga escape characters sa Java.  Line 10 will again write to the file.  This time "Pinoy Java Tutorial" naman.  And lastly, Line 11 closes the stream.  

So ang output nyan ay:

hi and hello from
Pinoy Java Tutorial

Now if wala yung "\n", ang magiging output ay:

hi and hello fromPinoy Java Tutorial

Kasi nga nawala yung new line.

Again, may iba pang way para makapag read and write.  Ito lang yung naisip ko na pinakamadali tandaan and pinaka maikli.  

That's it pancit. :)

2 comments:

  1. Good day Mau! Dont stop posting here some topics about Java Programming. Very very helpful to me. Aside from that, its translated in Filipino language. Lalo ko pa syang naiintindihan pag may mga topics akong di nagegets sa Java namin. I'm a college student. Request ko po sana na magpost kayo about collections and sa abstract. Medyo nalalabuan po ako dun. Thanks. More power.

    ReplyDelete
  2. Hi Mau! Please continue java programming topics it helps me so much to further understand it, Keep it up :))

    ReplyDelete