javaサンプルプログラム


バイナリファイルを作成する

import java.io.FileOutputStream;
import java.io.BufferedOutputStream;

public class WriteBynaryTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

        // 改行用の変数
        byte[] newline = new byte[]{ (byte)0x0D, (byte)0x00, (byte)0x0A, (byte)0x00 };

        try {
            BufferedOutputStream out = new BufferedOutputStream(
                                        new FileOutputStream("testoutFile.dat"));

            // BOM(Byte Order Mark) の書き込み
            out.write(new byte[]{(byte)0xFF,(byte)0xFE});

            // 2バイト/1文字 X 16文字
            byte[] tmpbyte = new byte[2];

            // "\uE000" から "\uF8FF" まで
            for( int i = 0xE0 ; i <= 0xF8; i++)
            {
                for(int j = 0; j <= 0xFF; j++)
                {
                    if( (j > 0) && (j % 16 == 0) )
                    {
                        // 改行
                        out.write(newline);
                        out.flush();
                    }
                    // リトルエンディアンで書き込む
                    tmpbyte[0] = (byte)j;
                    tmpbyte[1] = (byte)i;
                    out.write(tmpbyte);
                }
                // 改行
                out.write(newline);
                out.write(newline);
                out.flush();
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Which


import java.io.File;
public class Which {

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		if( args.length == 0 )
		{
			System.out.println( " Usage: java Which  programname " );
			System.exit( 1 );
		}

		String programName = args[0];
		boolean isExistsProgram = false;

		// メモ
		// Unix系とWindows系では、環境変数"PATH"のつづりが異なる。
		// - Unix系     :"PATH"
		// - Wndows系:"Path"
		// Windowsでは、ファイル名、環境変数の大文字小文字は無視するので、"PATH"で取得すれば、
		// 環境変数"Path"の値が取得できる。
		String envPath = System.getenv( "PATH" );
		String envPaths[] = envPath.split( File.pathSeparator );
		String concatPath = new String();

		for( String dir : envPaths )
		{
			if( ( dir.endsWith(File.separator) ) == false )
			{
				dir = dir + File.separator;
			}
			concatPath = dir + programName;
			File checkExistFile = new File( concatPath );
			if( checkExistFile.exists() )
			{
				System.out.println( checkExistFile );
				isExistsProgram = true;
				break;
			}
		}

		if( isExistsProgram == false )
		{
			System.out.println( "no " + programName + " in (" + envPath + ")" );
		}
	}
}

char型配列の値を比較する

package hello.com;

public class Helloworld
{
 	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		char[] officeCodeA = { 'Z', 'A' };
		char[] officeCodeB = { 'Z', 'A' };
		char[] officeCodeC = { 'Z', 'B' };
		char[] officeCodeD = { 'Z', 'A', 'B' };
		char[] officeCodeE = { 'Z' };

		// 表示用変数
		String strOfficeCodeA = new String( officeCodeA );
		String strOfficeCodeB = new String( officeCodeB );
		String strOfficeCodeC = new String( officeCodeC );
		String strOfficeCodeD = new String( officeCodeD );
		String strOfficeCodeE = new String( officeCodeE );
		
		// 文字列比較簡易版
		System.out.println( "( " + strOfficeCodeA + " )" + " - " +
							"( " + strOfficeCodeB + " ) : " +
							easyCompareCharArray( officeCodeA, officeCodeB ) );

		System.out.println( "( " + strOfficeCodeA + " )" + " - " +
							"( " + strOfficeCodeC + " ) : " +
							easyCompareCharArray( officeCodeA, officeCodeC ) );

		System.out.println( "( " + strOfficeCodeA + " )" + " - " +
							"( " + strOfficeCodeD + " ) : " +
							easyCompareCharArray( officeCodeA, officeCodeD ) );

		System.out.println( "( " + strOfficeCodeA + " )" + " - " +
							"( " + strOfficeCodeE + " ) : " +
							easyCompareCharArray( officeCodeA, officeCodeE ) );	
 		System.out.println("-------------------------------------------------");

		System.out.println( "( " + strOfficeCodeA + " )" + " - " +
							"( " + strOfficeCodeB + " ) : " +
							compareCharArray( officeCodeA, officeCodeB, officeCodeA.length ) );

		System.out.println( "( " + strOfficeCodeA + " )" + " - " +
							"( " + strOfficeCodeC + " ) : " +
							compareCharArray( officeCodeA, officeCodeC, officeCodeA.length ) );

		System.out.println( "( " + strOfficeCodeA + " )" + " - " +
							"( " + strOfficeCodeD + " ) : " +
							compareCharArray( officeCodeA, officeCodeD, officeCodeA.length ) );
	}

	// 文字列比較簡易版
	public static int easyCompareCharArray(char[] charRef, char[] charDif)
	{
		String strRef = new String( charRef );
		String strDif = new String( charDif );

		return strRef.compareTo( strDif );
	}

	// 文字列の長さが同じ場合の比較関数
	public static int compareCharArray(char[] charRef, char[] charDif, int compareSize)
	{
		int indexA = 0;
		int indexB = 0;
		int returnValue = 0;
		int ref_lastIndex = compareSize - 1;
		int dif_lastIndex = compareSize - 1;

		for( ; charRef[indexA] == charDif[indexB]; indexA++, indexB++)
		{
			// 比較元char配列、もしくは、比較先char配列の終端に達した。
			if( (indexA == ref_lastIndex) || (indexB == dif_lastIndex) )
			{
				break;
			}
			
		}

		returnValue = charRef[indexA] - charDif[indexB];
		return returnValue;
	}

}


XML ファイルを DOMによって操作する

//以下のようなXML文書を想定
//<?xml version="1.0" encoding="UTF-8"?>
//<MyBrowser version="1.0">
//    <MyBrowserAuth>
//        <AuthList>
//            <Opera>
//                <ReferrenceAuth>true</ReferrenceAuth>
//                <SearchAuth>true</SearchAuth>
//                <InsertAuth>true</InsertAuth>
//                <PrintAuth>true</PrintAuth>
//            </Opera>
//            <Firefox>
//                <ReferrenceAuth>true</ReferrenceAuth>
//                <SearchAuth>false</SearchAuth>
//                <InsertAuth>true</InsertAuth>
//                <PrintAuth>false</PrintAuth>
//            </Firefox>
//        </AuthList>
//    </MyBrowserAuth>
//</MyBrowser>

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory;  
//import javax.xml.parsers.FactoryConfigurationError;  
import javax.xml.parsers.ParserConfigurationException;
 
import org.xml.sax.SAXException;  
import org.xml.sax.SAXParseException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
//import org.w3c.dom.DOMException;


// For write operation
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;

import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import java.io.*;

public class AuthXmlEdit 
{
    // Global value so it can be ref'd by the tree-adapter
    // static Document document;

    public AuthXmlEdit() {
        
    }
    
    protected String[] strAuthTagName = { "ReferrenceAuth",
                                         "SearchAuth",
                                         "InsertAuth",
                                         "PrintAuth"
    };
    
    public static final String strOneTab = "\t";
    public static final String strTwoTab = "\t\t";
    public static final String strThreeTab = "\t\t\t";
    public static final String strFourTab = "\t\t\t\t";
    public static final String strFiveTab = "\t\t\t\t\t";
    
    
    public static void main (String argv [])
    {
        if (argv.length != 1) {
            System.err.println ("Usage: java TransformationApp filename");
            System.exit (1);
        }

        // DocumentBuilderFactory の新しいインスタンスを取得します。
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //factory.setNamespaceAware(true);
        //factory.setValidating(true);
 
        try {
            File f = new File(argv[0]);
 
            AuthXmlEdit authXmlEdit = new AuthXmlEdit();
            // DocumentBuilder の新しいインスタンスを作成します
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 指定されたファイルの内容を XML ドキュメントとして構文解析し、新しい DOM オブジェクトを返します。
            Document document = builder.parse(f);
 
            System.out.println("---------------------");
            authXmlEdit.printAuth( document );
            System.out.println("---------------------");

            try {
                // XPATH テスト
                XPathFactory xPathFactory = XPathFactory.newInstance();
                XPath xpath = xPathFactory.newXPath();
                XPathExpression xPathExpr = xpath.compile("/MyBrowser/MyBrowserAuth/AuthList/Opera/ReferrenceAuth/text()");
                Object result = xPathExpr.evaluate(document, XPathConstants.NODESET);
                NodeList nodes = (NodeList) result;
                System.out.println("<before>");
                for (int i = 0; i < nodes.getLength(); i++) {
                    System.out.println(nodes.item(i).getNodeValue());
                }

                System.out.println("<set>");
                nodes.item(0).setNodeValue("12334");
                System.out.println(nodes.item(0).getNodeValue());
                
                result = xPathExpr.evaluate(document, XPathConstants.NODESET);
                nodes = (NodeList) result;
                System.out.println("<after evaluate>");
                for (int i = 0; i < nodes.getLength(); i++) {
                    System.out.println(nodes.item(i).getNodeValue());
                }
                String str = xpath.evaluate("/MyBrowser/MyBrowserAuth/AuthList/Opera/ReferrenceAuth/text()", document );
                System.out.println("str : " + str );
                //XPathExpression expr = xpath.compile("//MyBrowser/MyBrowserAuth/AuthList/Opera/ReferrenceAuth/text()");
            } catch ( Exception ex ) {
                ex.printStackTrace();
            }
            
            // Use a Transformer for output
            TransformerFactory tFactory =
                TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
 
            DOMSource source = new DOMSource(document);
 
            StreamResult result = new StreamResult(System.out);
            transformer.transform(source, result);
           
                   
        } catch (TransformerConfigurationException tce) {
           // Error generated by the parser
           System.out.println ("\n** Transformer Factory error");
           System.out.println("   " + tce.getMessage() );

           // Use the contained exception, if any
           Throwable x = tce;
           if (tce.getException() != null)
               x = tce.getException();
           x.printStackTrace();
      
        } catch (TransformerException te) {
           // Error generated by the parser
           System.out.println ("\n** Transformation error");
           System.out.println("   " + te.getMessage() );

           // Use the contained exception, if any
           Throwable x = te;
           if (te.getException() != null)
               x = te.getException();
           x.printStackTrace();
           
        } catch (SAXParseException spe) {
           // Error generated by the parser
           System.out.println("\n** Parsing error"
              + ", line " + spe.getLineNumber()
              + ", uri " + spe.getSystemId());
           System.out.println("   " + spe.getMessage() );

           // Use the contained exception, if any
           Exception  x = spe;
           if (spe.getException() != null)
               x = spe.getException();
           x.printStackTrace();

         } catch (SAXException sxe) {
           // Error generated by this application
           // (or a parser-initialization error)
           Exception  x = sxe;
           if (sxe.getException() != null)
               x = sxe.getException();
           x.printStackTrace();

        } catch (ParserConfigurationException pce) {
            // Parser with specified options can't be built
            pce.printStackTrace();

        } catch (IOException ioe) {
           // I/O error
           ioe.printStackTrace();
        }

    } // main  

    protected void printAuth( Document document ) {
        
        int intTabStep = 0;
        // 文書の文書要素になっている子ノードへの直接アクセスを可能にする便利な属性です。 
        Element root = document.getDocumentElement();
        String  name = root.getNodeName();
        
        System.out.println( "ノード名:" + name );
        
        // このノードの子をすべて含む NodeList です。子が存在しない場合、ノードを持たない NodeList が返されます。 
        //NodeList childNodeLists = root.getChildNodes();
        
        intTabStep += 1;
        printAuthDetail( root, intTabStep );
    }
    
    // protected void printAuthDetail( Node node ) {
    protected void printAuthDetail( Node node, int intTabStep ) {
        
        NodeList childNodeList = node.getChildNodes();
        int count = childNodeList.getLength();

        for(int i=0; i<count; i++){ 
            Node childNode = childNodeList.item( i );
            String nodeName = childNode.getNodeName();
            String nodeValue = childNode.getNodeValue();
            String strTab = "";
 
            // 要素ノードの場合
            if( childNode.getNodeType() == Node.ELEMENT_NODE ){
                
                strTab = makeTabString( intTabStep );
                System.out.print( strTab );
                System.out.println("ノード名:" + nodeName);
                
                // 下の階層に行くため、タブの数を増やす。
                intTabStep += 1;
                // 再帰呼び出し
                printAuthDetail( childNode, intTabStep );
                intTabStep -= 1;
                //printAuthDetail(childNode);
            }

            // テキストノードの場合
            if( childNode.getNodeType() == Node.TEXT_NODE ){
                //System.out.println("ノード名:" + nodeName);
                //System.out.println("ノード値:" + nodeValue);

                boolean isParentAuthNode = isAuthNode( childNode );
                if( isParentAuthNode ) {
                    strTab = makeTabString( intTabStep );
                    System.out.print( strTab );
                    System.out.println("ノード値:" + nodeValue);
                }

            }
        }
    }
    
    protected boolean isAuthNode( Node node ) {
        // 親ノードが、以下の要素ノードの場合のみ、true
        // - ReferrenceAuth
        // - SearchAuth
        // - InsertAuth
        // - PrintAuth
        boolean isParentAuthNode = false;
        Node parentNode = node.getParentNode();
        String strParentNodeName = parentNode.getNodeName();
        
        for( int i = 0; i < strAuthTagName.length; i++ ) {
            if( strAuthTagName[i].equals(strParentNodeName) ) {
                isParentAuthNode = true;
                break;
            }
        }
        return isParentAuthNode;
    }
    
    protected String makeTabString( int intTabStep ) {
        
        String strTab = "";
        
        switch( intTabStep ) {
            case 1 :
                strTab = strOneTab;
                break;
            case 2 :
                strTab = strTwoTab;
                break;
            case 3 :
                strTab = strThreeTab;
                break;
            case 4 :
                strTab = strFourTab;
                break;
            case 5 :
                strTab = strFiveTab;
                break;
            default :
                // 何もしない
                break;
        }
        return strTab;
    }
// 参考URL
// http://www.technotype.net/tutorial/tutorial.php?fileId={DOM}&sectionId={traversing-the-node-tree}
}

半角文字(半角英数字、半角記号、半角カタカナ)を全角文字に変換作成する

import java.util.HashMap;



public class HalfwidthConvertTest {

    private static HashMap<String, String> mapKatakanaToFullWidth = null;


    /**
     * @param args
     */
    public static void main( String[] args ) {
        
        // 半角カタカナから全角カタカナ変換マップの作成
        // 参考URL
        // http://pgcafe.moo.jp/JAVA/string/main_1.htm
        HalfwidthConvertTest.mapKatakanaToFullWidth = new HashMap<String, String>();
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ア",  "ア" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "イ",  "イ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ウ",  "ウ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "エ",  "エ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "オ",  "オ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "カ",  "カ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "キ",  "キ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ク",  "ク" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ケ",  "ケ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "コ",  "コ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "サ",  "サ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "シ",  "シ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ス",  "ス" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "セ",  "セ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ソ",  "ソ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "タ",  "タ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "チ",  "チ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ツ",  "ツ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "テ",  "テ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ト",  "ト" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ナ",  "ナ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ニ",  "ニ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ヌ",  "ヌ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ネ",  "ネ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ノ",  "ノ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ハ",  "ハ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ヒ",  "ヒ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "フ",  "フ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ヘ",  "ヘ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ホ",  "ホ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "マ",  "マ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ミ",  "ミ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ム",  "ム" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "メ",  "メ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "モ",  "モ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ヤ",  "ヤ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ユ",  "ユ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ヨ",  "ヨ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ワ",  "ワ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ヲ",  "ヲ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ン",  "ン" );

        // 小書き文字
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ァ",  "ァ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ィ",  "ィ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ゥ",  "ゥ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ェ",  "ェ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ォ",  "ォ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ャ",  "ャ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ョ",  "ョ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ュ",  "ュ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ッ",  "ッ" );

        // 濁音のカタカナ
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ガ", "ガ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ギ", "ギ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "グ", "グ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ゲ", "ゲ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ゴ", "ゴ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ザ", "ザ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ジ", "ジ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ズ", "ズ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ゼ", "ゼ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ゾ", "ゾ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ダ", "ダ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ヂ", "ヂ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ヅ", "ヅ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "デ", "デ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ド", "ド" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "バ", "バ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ビ", "ビ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ブ", "ブ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ベ", "ベ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ボ", "ボ" );

        // 半濁音のカタカナ
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "パ", "パ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ピ", "ピ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "プ", "プ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ペ", "ペ" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "ポ", "ポ" );

        // 記号
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "「",  "「" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "」",  "」" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "、",  "、" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "。",  "。" );
        HalfwidthConvertTest.mapKatakanaToFullWidth.put( "・",  "・" );

        String strTarget = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
        executeTest( strTarget );
        strTarget = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨワヲンァィゥェォャョュッガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ「」、。・";
        executeTest( strTarget );
    }

    private static void executeTest( String strBeforeString ) {
        System.out.println( "変換前:" + strBeforeString );
        String afterString = convertToFullWidth( strBeforeString );
        System.out.println( "変換後:" + afterString );
    }

    // 参考URL 
    // Java:全角数字を半角数字へ変換する方法
    //   http://write-remember.com/program/java/changenumfulltohalf/
    // 全角半角変換(英数字の場合)
    //   http://ameblo.jp/archive-redo-blog/entry-10376390355.html
    // 半角文字のみ、全角文字に変換する。
    // それ以外の文字は変更しない。
    private static String convertToFullWidth( String strTarget )
    {
        StringBuffer sb = new StringBuffer();
        int intTargetWordCount = strTarget.length();

        for ( int i = 0; i < intTargetWordCount; i++ )
        {
            int intTarget = ( int )strTarget.charAt( i );
            char charTarget = strTarget.charAt( i );

            // " "(0x0020 半角空白:SPACE)の場合は、" "(0x3000 全角空白: IDEOGRAPHIC SPACE)に置き変える。
            if( intTarget == ' ' )
            {
                sb.append( ' ' );
                continue;
            }
            // 半角英数字かどうかのチェック
            // "!"(0x21 感嘆符:EXCLAMATION MARK)から"~"(0x7E チルダ:TILDE)の間の文字の場合は、
            // 全角文字に変換する。
            else if( (intTarget >= '!') && (intTarget <= 0x7E) )
            {
                charTarget = ( char )( intTarget + 0xFEE0 );
                intTarget = intTarget + 0xFEE0;
                sb.append( charTarget );
                continue;
            }
            else
            {
                String strCovertTarget = String.valueOf( charTarget );

                // 半角句読点、半角カタカナ、半角濁点、半角半濁点かどうかのチェック
                //
                // "。"(0xFF61 半角句点:HALFWIDTH IDEOGRAPHIC FULL STOP)から
                // "゚"(0xFF9F 半角半濁点:HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK)
                // の間の文字かどうかで判別できる。
                // これらの文字は、"Halfwidth and Fullwidth Forms" ブロックに文字が配置されている。
                if( intTarget >= '。' && intTarget <= '゚')
                {
                    // 最終文字から1文字前までの文字かどうかのチェック。
                    // (最終文字の場合は、次の文字は存在しない)
                    if( i <= (intTargetWordCount - 2) )
                    {
                        // 次の文字が濁音("゙")か半濁音("゚")の場合は、次の文字とあわせて
                        // 1文字と考える。
                        char charNextTarget = strTarget.charAt( i + 1 );
                        if( charNextTarget == '゙' || charNextTarget == '゚' )
                        {
                            // 半角カタカナ + 濁音("゙")か半濁音("゚") で 2文字なので、
                            // 新しいchar配列を作成し、String文字列に変換する
                            char[] charTestTarget = new char[2];
                            charTestTarget[0] = charTarget;
                            charTestTarget[1] = charNextTarget;
                            strCovertTarget = String.valueOf( charTestTarget );
                            // 濁音("゙")か半濁音("゚")のみの全角文字は存在しないので、
                            // 濁音("゙")か半濁音("゚")の次の文字に進めるための準備。
                            i++;
                        }
                    }

                    if( mapKatakanaToFullWidth.containsKey(strCovertTarget) )
                    {
                        // 半角カタカナに対応する全角カタカナの文字を取得する
                        strCovertTarget = mapKatakanaToFullWidth.get( strCovertTarget );
                    }

                    // 返却用文字列に追加する。
                    sb.append( strCovertTarget );
                }
            }
        }
        return sb.toString();
    }
}

// Unicode Normalization Forms
// http://www.unicode.org/reports/tr15/

入力されたIPアドレス(IpV4)を0埋めされた IPアドレス表記に変換する

package hello.com;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Helloworld
{
    public static void main(String[] args)
    {
        paddingIPV4();
    }

    public static void paddingIPV4()
    {
        // IPアドレス(IPV4)の正規表現
        String IPV4Pattern = "((1?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}(1?\\d\\d?|2[0-4]\\d|25[0-5])";
        Pattern pattern = Pattern.compile(IPV4Pattern);

        Scanner scanner = new Scanner(System.in);
        String inputString;
        
        while (true)
        {
            System.out.print("サーバーのIPアドレス(IPv4)を入力してください:");

            inputString = scanner.nextLine();

            Matcher matcher = pattern.matcher(inputString);
            boolean isMatch = matcher.matches();
            
            if (isMatch)
            {
                break;
            }
            else {
                System.out.print("入力形式に誤りがあります");
            }
        }

        scanner.close();
        
        // 入力したIPアドレスを "."文字で分割
        String[] ipV4_Parts = inputString.split("\\.");

        // いったん、3桁の文字列(3桁に満たない場合は半角空白で)整形する
        String oneSegment = String.format("%3s", ipV4_Parts[0]);
        String twoSegment = String.format("%3s", ipV4_Parts[1]);
        String threeSegment = String.format("%3s", ipV4_Parts[2]);
        String fourSegment = String.format("%3s", ipV4_Parts[3]);
        
        // 半角空白文字を 0 に変換
        oneSegment = oneSegment.replace(" ", "0");
        twoSegment = twoSegment.replace(" ", "0");
        threeSegment = threeSegment.replace(" ", "0");
        fourSegment = fourSegment.replace(" ", "0");
        
        // 0埋めした文字列を再連結
        String paddingIpV4 = oneSegment + "." +
                                twoSegment + "." +
                                threeSegment + "." +
                                fourSegment;

        System.out.println("0埋めした IPV4アドレス:" + paddingIpV4);

        // 参考資料
        // - 【Java】文字列のパディング
        // https://qiita.com/kikkutonton/items/400dcfc343864028800e
    }
}

// Java:ゼロ埋め、半角スペース埋めする方法
// http://write-remember.com/program/java/format/

タグ:

java xml
最終更新:2020年12月19日 22:42