String.indexOf()抛出StringIndexOutOfBoundsException

时间:2015-03-23 02:40:41

标签: java string

在下面的程序中,我必须首先读取一个文件,然后再编写它。在运行配置中,我提供了文件的路径,但是当我运行程序时,它会给出错误:String index out of range: -1。 ?请帮忙

public static void main(String[] args) throws IOException{

String fileName = args[0];
    Scanner filescan;//to read the file
    filescan=new Scanner(new File(fileName));//read the whole file

FileWriter fstream = new FileWriter(fileName.subSequence(0,fileName.indexOf(".uniqe.ICext"))+".uniqe.Mpwm");
    BufferedWriter mpwm = new BufferedWriter(fstream);

1 个答案:

答案 0 :(得分:1)

你应该在使用substring之前添加验证。否则最终会抛出异常

int i= fileName.indexOf(".uniqe.ICext");
if(i<0)
    //file name can't substring or handle exception
else
    FileWriter fstream = new FileWriter(fileName.subSequence(0,i)+".uniqe.Mpwm");