Here you can find the source of renameFile(final File path, final String fname)
Parameter | Description |
---|---|
path | directory of the file |
fname | file name |
Parameter | Description |
---|---|
IOException | an exception |
public static File renameFile(final File path, final String fname) throws IOException
//package com.java2s; /*========================================================================= /*from ww w. j av a 2 s . c o m*/ Copyright ? 2013 BIREME/PAHO/WHO This file is part of TabNetCells. TabNetCells is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. TabNetCells is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with TabNetCells. If not, see <http://www.gnu.org/licenses/>. =========================================================================*/ import java.io.File; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { /** * Renames a file if the name alread exists. Add an index to the name. * xxxx.txt -> xxxx(1).txt * xxxx(1).txt -> xxxx(2).txt * @param path directory of the file * @param fname file name * @return a File object with the file name chenged * @throws IOException */ public static File renameFile(final File path, final String fname) throws IOException { if (path == null) { throw new NullPointerException("path"); } if (fname == null) { throw new NullPointerException("fname"); } final int dotIndex = fname.lastIndexOf('.'); final String prefix = (dotIndex == -1) ? fname : fname.substring(0, dotIndex); final String suffix = (dotIndex == -1) ? "" : fname.substring(dotIndex); final Pattern pat = Pattern.compile(prefix + "\\((\\d+)\\)" + suffix); final Matcher mat = pat.matcher(""); final String[] fNames = path.list(); int last = 0; for (String name : fNames) { mat.reset(name); if (mat.matches()) { final int idx = Integer.parseInt(mat.group(1)); if (last < idx) { last = idx; } } } final String nName = prefix + "(" + (last + 1) + ")" + suffix; final File nfile = new File(path, nName); if (nfile.exists()) { throw new IOException("renameFile failed. File=[" + nName + "]"); } return nfile; } }