Home > JAVA > ภาษา java แสดงไฟล์ในไดเรกทอรี

ภาษา java แสดงไฟล์ในไดเรกทอรี

March 25, 2010 1 Comment »    

ในบทความนี้จะใช้ภาษา java ในการอ่านไฟล์ใน directory ที่เราต้องการว่ามีไฟล์อะไรบ้างโดยการสร้าง File object เพื่อใช้ในการอ่านรายชื่อไฟล์ใน directory ที่เราต้องการออกมาต่อไปเราก็ไปดูตัวอย่างภาษาจาวากันเลย


import java.io.*;

public class DirListing

{

private static void dirlist(String fname){

File dir = new File(fname);

String[] child = dir.list();

if(child == null){

System.out.println("Specified directory does not exist");

System.exit(0);

}

else{

for(int i = 0 ; i < child.length; i++)

{

String fileName = child[i];

System.out.println(fileName);

}

}

}

public static void main(String[] args){

switch(args.length){

case 0: System.out.println("Direcoty has not mentioned");

System.exit(0);

case 1: dirlist(args[0]);

System.exit(0);

default: System.out.println("Multiple files are not allow");

System.exit(0);

}

}

}

java, list directory java, java example

จากการรันโปรแกรมจะเห็นว่าเราต้องใส่ชื่อพาธของ directory ลงไปจากนั้นก็จะแสดงชื่อไฟล์ทั้งหมดออกมาจาก โค้ดตัวอย่างเราได้มีการใช้ object File โดยใช้ method list() เพื่อแสดงรายชื่อไฟล์ทั้งหมดออกมาซึ่งจะได้ ออกมาเป็น Array ที่เก็บ string ชื่อไฟล์ไว้ดังนั้นต้องใช้ loop for เพื่อแสดงออกมาจนหมด

Download SourceCode

Tags: , , , , ,

Comments : ภาษา java แสดงไฟล์ในไดเรกทอรี

Comments:0

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=""> <strike> <strong>

Trackbacks:1

Listed below are links to weblogs that reference ภาษา java แสดงไฟล์ในไดเรกทอรี

pingback from Tweets that mention ภาษา java แสดงไฟล์ในไดเรกทอรี: ในบทความนี้จะใช้ภาษา java ในการอ่านไฟล์ใน directory ที่เราต้องกา March 27, 2010

[...] This post was mentioned on Twitter by sutiwat. sutiwat said: ภาษา java แสดงไฟล์ในไดเรกทอรี: ในบทความนี้จะใช้ภาษา java ในการอ่านไฟล์ใน directory ที่เราต้องการว่ามีไฟล์อะไรบ้างโ… http://bit.ly/cZzBkk [...]