プログラミングB


webにアクセスするプログラム, iCal形式で予定をファイルに書き込むプログラム, 予定をJSON形式でファイルに記述したものを読み込み、iCal形式に変換するプログラム, Google Chromeの「ブックマーク」からマークダウン形式のリンク集を作成するプログラム, マークダウン形式のファイルをHTML形式のファイルに変換するプログラム

関連リンク

行番号付きでソースプログラムをWordにコピーする方法

VSCodeにCopyWithLineNumbers拡張機能をインストール

  1. 拡張機能のアイコンをクリックします。
  2. 拡張機能ビュー上部のテキストボックスに「Copy With」と入力します。 表示される拡張機能の中から「Copy With Line Numbers」を見つけ、インストールボタンをクリックします。

VSCodeからWordへのコピー

  1. Wordでソースプログラムを挿入したい箇所に、1行1列の表を挿入しておく。
  2. VSCodeで表示中のソースプログラムを選択する。
  3. メニュー「表示」-「コマンドパレット...」を選択し、上部のテキストボックスに「Copy」と入力する。 表示されたコマンドの中から、「Copy With Line Numbers: Without Path」をクリックする。
  4. Wordに戻り、表の中のカーソル位置で右クリックする。 表示される項目の中から貼り付けのオプションの「テキストのみ保持」をクリックする。
  5. すると、行番号付きのソースプログラムが表の中に挿入される。

webにアクセスするプログラム

Web_access_with_proxy.java(Proxyを経由する場合)
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
  
public class Web_access_with_proxy {
    public static void main(String[] args) {
        HttpURLConnection con = null;
        StringBuffer result = new StringBuffer();
  
        try {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("202.250.64.133", 10080)); // http://ccproxyz.kanagawa-it.ac.jp:10080
  
            URL url = new URL("https://www.kait.jp");
            con = (HttpURLConnection) url.openConnection(proxy);
  
            con.setRequestMethod("GET");
            con.connect();
  
            int status = con.getResponseCode();
            if (status == HttpURLConnection.HTTP_OK) {
                InputStream in = con.getInputStream();
                String encoding = con.getContentEncoding();
  
                if(null == encoding){
                    encoding = "UTF-8";
                }
  
                InputStreamReader inReader = new InputStreamReader(in, encoding);
                BufferedReader bufReader = new BufferedReader(inReader);
  
                String line = null;
                while((line = bufReader.readLine()) != null) {
                    result.append(line);
                }
                bufReader.close();
                inReader.close();
                in.close();
            }
            else {
                System.out.println(status);
            }
  
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {
            if (con != null) {
                // コネクションを切断
                con.disconnect();
            }
        }
  
        System.out.println("result=" + result.toString());
    }
}
    

Web_access.java(Proxyを経由しない場合)
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
  
public class Web_access {
    public static void main(String[] args) {
        HttpURLConnection con = null;
        StringBuffer result = new StringBuffer();
  
        try { 
            URL url = new URL("https://www.kait.jp");
            con = (HttpURLConnection) url.openConnection();
  
            con.setRequestMethod("GET");
            con.connect();
  
            int status = con.getResponseCode();
            if (status == HttpURLConnection.HTTP_OK) {
                InputStream in = con.getInputStream();
                String encoding = con.getContentEncoding();
  
                if(null == encoding){
                    encoding = "UTF-8";
                }
  
                InputStreamReader inReader = new InputStreamReader(in, encoding);
                BufferedReader bufReader = new BufferedReader(inReader);
  
                String line = null;
                while((line = bufReader.readLine()) != null) {
                    result.append(line);
                }
                bufReader.close();
                inReader.close();
                in.close();
            }
            else {
                System.out.println(status);
            }
  
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {
            if (con != null) {
                // コネクションを切断
                con.disconnect();
            }
        }
  
        System.out.println("result=" + result.toString());
    }
}
    

iCal形式で予定をファイルに書き込むプログラム

以下の2つのライブラリ(jarファイル)をダウンロードし、libフォルダにコピーする必要があります。

iCalTest1.java
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
  
import biweekly.ICalVersion;
import biweekly.ICalendar;
import biweekly.component.VEvent;
import biweekly.io.text.ICalWriter;
import biweekly.property.Summary;
  
public class iCalTest1 {
    public static void main(String[] args) throws Exception {
        String savename = "sample.ics";
        DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
  
        ICalendar ical = new ICalendar();
  
        VEvent event1 = new VEvent();
        Summary summary1 = event1.setSummary("教室会議");
        summary1.setLanguage("jp");
        event1.setDateStart(df1.parse("2023-11-08 16:50"));
        event1.setDateEnd(df1.parse("2023-11-08 19:00"));
        ical.addEvent(event1);
        
        VEvent event2 = new VEvent();
        Summary summary2 = event2.setSummary("幾徳祭");
        summary2.setLanguage("jp");
        event2.setDateStart(df2.parse("2023-11-02"), false);
        event2.setDateEnd(df2.parse("2023-11-08"), false);
        ical.addEvent(event2);
  
        File file = new File(savename);
        ICalWriter writer = new ICalWriter(file, ICalVersion.V2_0);
        writer.write(ical);    
        writer.close();
    }
}
    

作成したiCal形式のファイルは、Google Calendarにインポートすることで予定を追加することができる。

  1. Google Calendarを開く。

  2. 右上の「設定メニュー」アイコンをクリックし、「設定」項目を選択する。

  3. 左側にある「インポート/エクスポート」をクリックする。

  4. 「パソコンからファイルを選択」ボタンをクリックし、「sample.ics」を選択する。そして、「インポート」ボタンをクリックする。

  5. すると、下記のように予定が追加されている。

予定をJSON形式でファイルに記述したものを読み込み、iCal形式に変換するプログラム

以下の3つのライブラリ(jarファイル)をダウンロードし、libフォルダにコピーする必要があります。

以下が、予定を記したJSON形式のファイルである。

schedule1.json
{
  
"events": [
        {
            "title": "教室会議",
            "start": "2023-11-08 16:50",
            "end": "2023-11-08 19:00"
        },
        {
            "title": "幾徳祭",
            "start": "2023-11-02",
            "end": "2023-11-08"
        }
    ]
  
}
    

iCalCreator.java
public class iCalCreator {
    public static void main(String[] args) throws Exception {
        String target = "schedule1.json";
        String savename = "schedule1.ics";
  
        iCal ical1 = new iCal(target);
        ical1.save(savename);
    }
}
    

iCal.java
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
  
import org.apache.commons.io.FileUtils;
  
import com.google.gson.Gson;
  
import biweekly.ICalVersion;
import biweekly.ICalendar;
import biweekly.component.VEvent;
import biweekly.io.text.ICalWriter;
  
public class iCal {
    private ICalendar ical;
  
    public iCal(String json_filename) throws Exception {
  
        File file = new File(json_filename);
        if (file.exists()) {
            String content = FileUtils.readFileToString(file, "UTF-8");
  
            Gson gson = new Gson();
            events e = gson.fromJson(content, events.class);
  
            List<event> list =  e.getEvents();
            int n = list.size();
            
            DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
  
            this.ical = new ICalendar();
  
            for (int i = 0; i < n; i++) {
                VEvent ve = new VEvent();
  
                event ev = list.get(i);
                ve.setSummary(ev.title);
  
                if (ev.start.length() >= 11) {
                    ve.setDateStart(df1.parse(ev.start));
                }
                else {
                    ve.setDateStart(df2.parse(ev.start), false);
                }
  
                if (ev.end.length() >= 11) {
                    ve.setDateEnd(df1.parse(ev.end));
                }
                else {
                    ve.setDateEnd(df2.parse(ev.end), false);
                }
  
                this.ical.addEvent(ve);
            }
        }
    }
  
    public void save(String savename) throws Exception {
        File file = new File(savename);
        ICalWriter writer = new ICalWriter(file, ICalVersion.V2_0);
        writer.write(this.ical);    
        writer.close();
    }
}
    

events.java
import java.util.List;
  
public class events {
    private List<event> events;
  
    public List<event> getEvents() {
		return events;
	}
}
    

event.java
public class event {
    public String title;
    public String start;
    public String end;
  
    public event(String title, String start, String end) {
        this.title = title;
        this.start = start;
        this.end = end;
    }
}
    

Google Chromeの「ブックマーク」からマークダウン形式のリンク集を作成するプログラム

以下のライブラリ(jarファイル)をダウンロードし、libフォルダにコピーする必要があります。

プログラムを動かす前に、以下の準備が必要です。

  1. Chromeのブックマークの「その他のブックマーク」内にフォルダ「info」とフォルダ「dummy」を作成する。 「info」の次に「dummy」が位置していれば、それ以外の制約はない。
  2. Chromeの画面右上にある縦に3点並んだアイコンをクリックする。 項目「ブックマークをエクスポート」を選択し、ブックマークをhtml形式で保存する。 今回、保存ファイル名は「bookmarks_2023_11_06.html」であったと仮定する。 bookmarks_2023_11_06.htmlを圧縮したものはここからダウンロードできます。

Extract1.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
  
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
  
public class Extract1 {
    public static void main(String[] args) throws Exception {
        String fn = "bookmarks_2023_11_06.html";
        String savename = "link_20231106.md";
        String title = "リンク集(2023/11/06)";
  
        File file = new File(fn);
  
        ArrayList<String> lines= new ArrayList<>();
  
        if (file.exists()) {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
  
            String content;
            while ((content = br.readLine()) != null) {
                lines.add(content);
                //System.out.println(content);
            }
            br.close();
  
            int total = lines.size();
            int startL = 0;
            for (int i = 0; i < total; i++) {
                int pos = lines.get(i).indexOf(">info</H3>");
                if (pos != -1) {
                    startL = i + 1;
                    break;
                }
            }
  
            int endL = 0;
            for (int i = 0; i < total; i++) {
                int pos = lines.get(i).indexOf(">dummy</H3>");
                if (pos != -1) {
                    endL = i + 1;
                    break;
                }
            }
  
            //System.out.println("start = " + startL + ", end = " + endL);
  
            String ss = "";
            for (int i = 0; i < (endL-1); i++) {
                if ((i+1) >= startL) {
                    ss = ss + lines.get(i).trim().replace("\n", "");
                }
            }
  
            //System.out.println(ss);
 
            Document doc = Jsoup.parse(ss);
            Elements ela = doc.select("a");
  
            File file2 = new File(savename);
            PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2),"UTF-8")));
  
            pw.println("# " + title + "\n");
            for (Element e: ela) {
                pw.println("* [" + e.text() + "](" + e.attr("href") + ")");
            }
            pw.close();
        }
        else {
            System.out.println("指定されたファイルは存在しません。");
        }
    }
}
    

link_20231106.md
# リンク集(2023/11/06)
  
* [エッジAIの処理速度を最大8倍に 漸進的物体検知技術: NECの最先端技術| NEC](https://jpn.nec.com/rd/technologies/202106/index.html)
* [NEC、エッジ機器の性能を引き出し、大量の映像から分析対象を高速・高精度に検知できる技術を開発 (2021年11月16日): プレスリリース | NEC](https://jpn.nec.com/press/202111/20211116_02.html)
* [処理に制約があるエッジ機器でも大量の映像から物体を検知─NECの「漸進的物体検知技術」 | IT Leaders](https://it.impress.co.jp/articles/-/22340)
    

マークダウン形式のファイルをHTML形式のファイルに変換するプログラム

以下の2つのライブラリ(jarファイル)をダウンロードし、libフォルダにコピーする必要があります。

md2html.java
import java.io.File;
  
import org.apache.commons.io.FileUtils;
  
import com.petebevin.markdown.MarkdownProcessor;
  
public class md2html {
    public static void main(String[] args) throws Exception {
        String target = "link_20231106.md";
        String savename = "link_20231106.html";
  
        File file = new File(target);
        if (file.exists()) {
            String fileContent = FileUtils.readFileToString(file, "UTF-8");
  
            MarkdownProcessor processor = new MarkdownProcessor();
            String htmlContent = processor.markdown(fileContent);
  
            File file2 = new File(savename);
            FileUtils.write(file2, htmlContent, "UTF-8");
        }
        else {
            System.out.println("指定のファイルは存在しません。");
        }
    }
}
    

link_20231106.html
<h1>リンク集(2023/11/06)</h1>
  
<ul>
<li><a href="https://jpn.nec.com/rd/technologies/202106/index.html">エッジAIの処理速度を最大8倍に 漸進的物体検知技術: NECの最先端技術| NEC</a></li>
<li><a href="https://jpn.nec.com/press/202111/20211116_02.html">NEC、エッジ機器の性能を引き出し、大量の映像から分析対象を高速・高精度に検知できる技術を開発 (2021年11月16日): プレスリリース | NEC</a></li>
<li><a href="https://it.impress.co.jp/articles/-/22340">処理に制約があるエッジ機器でも大量の映像から物体を検知─NECの「漸進的物体検知技術」 | IT Leaders</a></li>
</ul>