String类的substring方法

来源:互联网 发布:华夏网络工具包 编辑:程序博客网 时间:2024/06/05 19:02

最近遇到一道编程题,题目如下:

                  编写一个Java应用程序,程序运行后,要求到指定的文件夹(比如d:\work目录)查找后缀为java的文件,取出并保存到d:\test目录下。

思路如下:1.把d:\work目录下的文件或是子目录存放在File数组中(listFile()方法)

                    2.遍历File数组,判断此文件实例是否为标准文件(isFile())

                    3.若是标准文件,把此标准文件名转换为字符串(使用File类的getName()方法),判断字符串后4个字符是否为"java",若是把此文件复制到d:\test目录中

代码如下:

package lqb;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class COPY_JAVA {public static void main(String[] args) {copy("E:\\work","E:\\test");}public static void copy(String dir,String des){File f=new File(dir);File fd=new File(des);if(f.isDirectory()){File[] fs=f.listFiles();//把f目录中的文件和子目录实例都存入fs数组中for(int i=0;i<fs.length;i++)//遍历fs文件数组{if(fs[i].isFile()){String s=fs[i].getName();if(s.substring(s.length()-5, s.length()-1).equals("java")){File d=new File(fd,s);int  c;try {FileInputStream  fin=new FileInputStream(fs[i]);FileOutputStream fou=new FileOutputStream(d);while((c=fin.read())!=-1){fou.write(c);}fou.close();fin.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}else{System.out.println("不是目录");}}}


 

 

在运行的过程中遇到问题,代码中红色字符处,if判断条件总是为假,调试发现是substring(int beginindex,int endindex)方法用错了,第一个参数为子字符串开始处,而第二个参数为子字符串结束的后一位,即是substring 范围[beginindex,endindex-1]

 

java api

substring
public String substring(int beginIndex,
int endIndex)返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex。
示例:

"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"

参数:
beginIndex - 起始索引(包括)。
endIndex - 结束索引(不包括)。
返回:
指定的子字符串。
抛出:
IndexOutOfBoundsException - 如果 beginIndex 为负,或 endIndex 大于此 String 对象的长度,或 beginIndex 大于 endIndex。