學習JAVA第二十三天
阿新 • • 發佈:2021-08-24
檔案類
*建立File類物件
File f;
f = new File ("a.java");
f = new File ("C:\\nie\\","a.java");
*File類提供了實現目錄管理功能的方法
File path = new File("C:\\nie\\");
File f = new File(path,"a.java");
2.列出所有檔案
import java.io.*;class ListAllFiles
{
public static void main(String[] args){
ListFiles( new File( "c:\\workspace"));
} public static void ListFiles( File dir ){
if( !dir.exists() || ! dir.isDirectory() ) return;
String [] files = dir.list();
for( int i=0; i<files.length; i++){
File file = new File( dir, files[i] );
if( file.isFile() ){
System.out.println(
dir + "\\" + file.getName() + "\t" + file.length() );
}else{
System.out.println(
dir + "\\" + file.getName() + "\t<dir>" );
ListFiles( file ); //對於子目錄,進行遞迴呼叫
}
}
}
} 3.Pattern類 import java.util.regex.*;
public class RegexSplitter {
public static void main(String[] args) throws Exception {
Pattern p = Pattern.compile( "[, \\s]+");
String[] result =
p.split( "one,two, three four , five ");
for (int i=0; i<result.length; i++)
System.out.println(result[i]);
}
} 4.匹配 import java.util.regex.*;
public class RegexEmailValidate {
public static void main(String[] args)
throws Exception {
String pattern = "^[^@]+@[\\w]+(\\.[\\w]+)*$";
String email = "[email protected]";
boolean ok = Pattern.matches( pattern, email );
System.out.println( ok );
}
} 5.Matcher類 mport java.util.regex.*;
public class RegexReplacement {
public static void main(String[] args)
throws Exception {
Pattern pattern = Pattern.compile("cat");
Matcher matcher = pattern.matcher(
"one cat, two cats in the yard");
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, "big $0");
}
matcher.appendTail(sb);
System.out.println(sb.toString());
}
}