Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: How to append "test" to a filename (after path and before extension)? Date: Thu, 25 Aug 2011 07:30:02 -0400 Organization: A noiseless patient Spider Lines: 47 Message-ID: References: <4e561ae9$0$7610$9b4e6d93@newsspool1.arcor-online.net> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Thu, 25 Aug 2011 11:30:36 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="f8igmItKsWs6nM5YanFxAA"; logging-data="20042"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19FPuErbuWOINXYvY7mq+NT" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:6.0) Gecko/20110812 Thunderbird/6.0 In-Reply-To: <4e561ae9$0$7610$9b4e6d93@newsspool1.arcor-online.net> Cancel-Lock: sha1:8RkxiNlmUL8jPOs4Rb4cDNlqszk= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:7371 On 8/25/2011 5:50 AM, Jochen Brenzlinger wrote: > Let's start with a filename which is stored in a String variable e.g. > > String fn = "D:\project\java\testproj\log2011.log" Aside: Those backslash characters need some attention ... > I want to append "test" to the file basename but keep path and extension. > The resulting filename for the example above should be: > > string fn2 = "D:\project\java\testproj\log2011test.log" > > How can I do this programmatically from Java? A bare-bones approach: int dot = fn.lastIndexOf('.'); String fn2 = fn.substring(0, dot) + "test" + fn.substring(dot); In actual use you'd want some sanity checking to be sure the '.' is in fact present and is after the last '\', so you wouldn't get fooled by D:\project\java\testproj\config or D:\project\java\testproj.old\data You could guard against such things by using fn.lastIndexOf('\\') to locate the rightmost back-slash and checking that the '.' does in fact appear even further right. However, I think you're better off using the File class to chop up and reassemble file names in a (mostly) platform-independent way, e.g. File base = new File(fn); String name = base.getName(); // handles / or \ or whatever int dot = name.lastIndexOf('.'); String newname = (dot < 0) ? name + "test" : name.substring(0, dot) + "test" + name.substring(dot); File test = new File(base.getParentFile(), newname); String fn2 = test.getPath(); // if needed This may seem like a lot of running around for little effect, but it protects you from some unpleasant surprises in the long run. -- Eric Sosman esosman@ieee-dot-org.invalid