From 2d9857ce8ee370ba30a4968942c604c0127e705e Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 9 May 2004 23:26:43 +0000 Subject: [PATCH] added org.ibex.util.FileNameEncoder: safely escapes filenames darcs-hash:20040509232643-5007d-b64121307daab8d7a2e2c8772c338ca30943215e.gz --- src/org/ibex/util/FileNameEncoder.java | 50 ++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/org/ibex/util/FileNameEncoder.java diff --git a/src/org/ibex/util/FileNameEncoder.java b/src/org/ibex/util/FileNameEncoder.java new file mode 100644 index 0000000..e68bba2 --- /dev/null +++ b/src/org/ibex/util/FileNameEncoder.java @@ -0,0 +1,50 @@ +// Copyright (C) 2003 Adam Megacz all rights reserved. +// +// You may modify, copy, and redistribute this code under the terms of +// the GNU Library Public License version 2.1, with the exception of +// the portion of clause 6a after the semicolon (aka the "obnoxious +// relink clause") + +package org.ibex.util; +import java.util.*; +import java.io.*; + +/** provides commands to urlencode and urldecode strings, making sure + * to escape sequences which have special meanings in filenames */ +public class FileNameEncoder { + + private static final char[] hex = + new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + + public static String encode(String s) { + StringBuffer sb = new StringBuffer(); + try { + byte[] b = s.getBytes("UTF-8"); + for(int i=0; i 126 || c == '%' || (i == 0 && c == '.')) + sb.append("%" + hex[(b[i] & 0xf0) >> 8] + hex[b[i] & 0xf]); + else sb.append(c); + } + return sb.toString(); + } catch (UnsupportedEncodingException uee) { + throw new Error("this should never happen; Java spec mandates UTF-8 support"); + } + } + + public static String decode(String s) { + StringBuffer sb = new StringBuffer(); + byte[] b = new byte[s.length() * 2]; + int bytes = 0; + for(int i=0; i