Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    public static String decodeUrlToFS(String filename) {
        byte[] bArr = filename.getBytes();
        byte[] bDest = decode(bArr);
        try {
            return new String(bDest, "utf-8");
        } catch (UnsupportedEncodingException e) {
            return new String(bDest);
        }
    }

    public static byte[] decode(byte[] url) throws IllegalArgumentException {
        if (url.length == 0) {
            return new byte[0];
        }

        // Create a new byte array with the same length to ensure capacity
        byte[] tempData = new byte[url.length];

        int tempCount = 0;
        for (int i = 0; i < url.length; i++) {
            byte b = url[i];
            if (b == '%') {
                if (url.length - i > 2) {
                    b = (byte) (parseHex(url[i + 1]) * 16 + parseHex(url[i + 2]));
                    i += 2;
                } else {
                    throw new IllegalArgumentException("Invalid format");
                }
            }
            tempData[tempCount++] = b;
        }
        byte[] retData = new byte[tempCount];
        System.arraycopy(tempData, 0, retData, 0, tempCount);
        return retData;
    }

    private static int parseHex(byte b) {
        if (b >= '0' && b <= '9')
            return (b - '0');
        if (b >= 'A' && b <= 'F')
            return (b - 'A' + 10);
        if (b >= 'a' && b <= 'f')
            return (b - 'a' + 10);

        throw new IllegalArgumentException("Invalid hex char '" + b + "'");
    }
}