Java活用生活

ログイン

オンライン状況

オンラインユーザー1人
ログインユーザー0人
登録ユーザー2人

カウンタ

COUNTER332340

日誌

MyDoc(備忘録)
123456
2024/04/10

RowCallbackHandlerのサンプルを以下のようにしました。

固定リンク | by:aramaki
Qiita https://qiita.com/suema0331/items/e3ca75dff8e9118772bc のRowCallbackHandlerのサンプルを以下のようにしました。
------------------------------------------------------------------------------
public class AccountRowCallBackHandler implements RowCallbackHandler{
// CSV 出力パス
public static String PATH="rowcallback.csv";

@Override
public void processRow(ResultSet rs) throws SQLException {
// CSV出力のため、1行データは、配列に格納する。
// 全データ格納リスト
List<String[]> dataList=new ArrayList<>();
do {
String[] dataArray=new String[6];
dataArray[0]=String.valueOf(rs.getLong("ID"));
dataArray[1]=rs.getString("ACCOUNT_GROUP");
dataArray[2]=rs.getString("MAIL");
dataArray[3]=rs.getString("NAME");
dataArray[4]=rs.getString("PASSWORD");
dataArray[5]=rs.getString("USER_ID");
dataList.add(dataArray);
}while(rs.next());
write(dataList,PATH);
}
// CSVファイル書き込み処理
public void write(List<String[]> list,String outputPath){
File file=new File(outputPath);
Path path=file.toPath();
// CSV書き込み処理
try {
Files.write(path, list.stream().map(s -> String.join(",",s)).collect(Collectors.toList()),
StandardCharsets.UTF_8, // 文字コード
StandardOpenOption.WRITE, // 書込みモード
StandardOpenOption.CREATE, // ファイルがなければ新規作成
StandardOpenOption.TRUNCATE_EXISTING // すでにファイルがある場合は、ファイルを削除
);
} catch (IOException e) {
System.out.print("CSV書き出し失敗");
e.printStackTrace();
}
}

}

21:14 | 投票する | 投票数(0) | コメント(0)
2023/08/23

文字列と画像をpost送信(再掲・補足追加)

固定リンク | by:aramaki
文字列と画像をpost送信(再掲・捕捉追加)
----------------------------------------------------------------
以前、掲載した「PostMultipart.java」の補足追加版です
。このクラスの送信した文字列と画像は、サーバー側PHP(UTF-8)で処理します。
そのため、レスポンス文字列の先頭にBOMがあるため、そのため、BOM判定して、
BOMを除去しました。なお、connect()についても補足しています。

--------------------------------------------------------------------------------------------------
package multi.part.post;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
public class PostMultipart {
/** 改行コード */
private static final String LINE_FEED = "\r\n";
/** コンテンツ境界線 */
private String boundary;
/** HTTP接続インターフェイス */
private HttpURLConnection httpConnection;
/** 文字コード */
private String charset;
/** リクエスト出力ストリーム */
private OutputStream outputStream;
/** データをテキスト出力ストリームに出力する */
private PrintWriter writer;

// コンストラクタ
public PostMultipart(String requestUrl, String charset) throws IOException {
this.charset = charset;
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestUrl);
httpConnection = (HttpURLConnection) url.openConnection();

// 2023 08/20 追加
httpConnection.setRequestMethod("POST"); // これがなくても動作する

httpConnection.setUseCaches(false);
// リクエストボディー送信を許可
httpConnection.setDoOutput(true);
// レスポンスボディー受信許可
httpConnection.setDoInput(true);
httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

init();
}
// 初期処理
private void init() throws IOException{

// 2023 08/20 追加
//httpConnection.connect(); // これがなくても動作する
// connect()捕捉
// 接続されていない URLConnection に対して接続が必要な操作を行うと、 自動的に接続されます。
// 参照>http://fujimura2.fiw-web.net/java/appendix/net/URLConnection/index.html

outputStream = httpConnection.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
}

/**
* フォームフィールド追加
*
* @param name
*            パラメータ名
* @param value
*            パラメータ値
*/
public void addField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}

// 送信するファイルの追加
public void addFile(String name, File uploadFile) throws IOException {
FileInputStream inputStream = null;
try {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();

// 指定ファイルと取り込み、出力ストリームに出力する
inputStream = new FileInputStream(uploadFile);

// 読込みバッファ
byte[] buffer = new byte[4096];
int byteRead = -1;
while ((byteRead = inputStream.read(buffer)) != -1) {
// データをサーバーリクエストへ書き込み
outputStream.write(buffer, 0, byteRead);
}
outputStream.flush();
writer.append(LINE_FEED);
writer.flush();
} finally {
if (inputStream != null) {
inputStream.close();
}
//以下をコメントインするとhttpConnectionを切断するのでサーバーにデータが送信されない
// if (outputStream != null) {
// outputStream.close();
// }
}
}
//

/**
* ヘッダー追加
*
* @param name
*            ヘッダー名
* @param value
*            ヘッダー値
*/
public void addHeader(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();

}

/**
* POST 送信処理
*
* @return
* @throws IOException
*/
public List<String> post() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();

boolean isBomFlg=false;
// サーバーステイタスコードチェック
int status = httpConnection.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
String line = null;
//int cnt=0;
while ((line = reader.readLine()) != null) {
if(isBomFlg==false){
if(isBomLine(line)){
isBomFlg=true;
// BOMの先頭行はスキップ
continue;
}
}
response.add(line);
}
reader.close();
httpConnection.disconnect();
} else {
throw new IOException("Send Fail: " + status);
}
return response;
}

// サーバー側から(PHP)レスポンスで返される文字列にBOMがあるか判定する。
    private boolean isBomLine(String line){

        if(line==null || line.trim().length()==0){
            return false;
        }
        // レスポンス文字列をバイト配列に変換する。
        byte[] lineToByte=line.getBytes();
        int size=lineToByte.length;

        // 変換したバイト配列の要素数でない場合、BOM文字の数値ではないので、falseを返す。
        if(size!=3){
            return false;
        }
        // byte値をint型に変換した各要素を代入するへ配列変数
        int[] charCode=new int[3];
        for(int i=0;i<size;i++){
            charCode[i]=new Byte(lineToByte[i]).intValue();
        }
        if((-17==charCode[0]) && (-69 == charCode[1]) && (-65 == charCode[2])) {
            return true;
        }

        return false;

    }




}

11:50 | 投票する | 投票数(0) | コメント(0)
2023/03/16

HttpURLConnectionのまとめ

固定リンク | by:aramaki
HttpURLConnectionのまとめ
-----------------------------------------------------------

以下のサイトの 抜粋です。詳細は、下のアドレスにアクセスし、検証、動確してください。
    https://qiita.com/Hyman1993/items/bdf5500acff17f2b4840

----------------------- GET ----------------------------
    String getUrl = "https://github.com/Hyman1993";
        URL url = new URL(getUrl);
        //connectionのインスタンス
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //リクエストのメソッドを指定
        connection.setRequestMethod("GET");
        //通信開始
        connection.connect();
        // レスポンスコードを戻る
        int responseCode = connection.getResponseCode();
        // レスポンスコードを判断する、OKであれば、進める
        if(responseCode == HttpURLConnection.HTTP_OK){
              // 通信に成功した
              // テキストを取得する
              InputStream in= connection.getInputStream();
              String encoding = con.getContentEncoding();
              if(null == encoding){
                  encoding = "UTF-8";
              }
          StringBuffer result = new StringBuffer();
          final InputStreamReader inReader = new InputStreamReader(in, encoding);
          final BufferedReader bufReader = new BufferedReader(inReader);
          String line = null;
          // 1行ずつテキストを読み込む
          while((line = bufReader.readLine()) != null) {
              result.append(line);
          }
          //  クローズ
          bufReader.close();
          inReader.close();
          in.close();
          // アウトプット
          Log.log("result=============:"+result);
        }
      ---------------------------- POST -----------------------------
       String postUrl = "https://github.com/Hyman1993";
            URL url = new URL(postUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //POSTに指定
            connection.setRequestMethod("POST");
            //POST出力可能
            connection.setDoOutput(true);
            //入力可能
            connection.setDoInput(true);
            //cache無し
            connection.setUseCaches(false);
      // データタイプをjsonに指定する
      connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            //コネクション、通信開始
            connection.connect();
            // jsonデータを出力ストリームへ書き出す
       String body = "userName=hyman1993&password=123456";
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            writer.write(body);
            writer.close();

            int responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                      // 通信に成功した
              // GETメソッドを同様に
            }

      ------------------------------- ファイルのアップロード -------------------------------------------------------
        String postUrl = "https://github.com/Hyman1993";
        URL url = new URL(postUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-Type", "file/*");
        connection.connect();

        OutputStream outputStream = connection.getOutputStream();
        FileInputStream fileInputStream = new FileInputStream("file");
        int length = -1;
        byte[] bytes = new byte[1024];
        while ((length = fileInputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,length);
        }
        fileInputStream.close();
        outputStream.close();

        int responseCode = connection.getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK){
                     // 通信に成功した
                     // GETメソッドを同様に
        }
20:50 | 投票する | 投票数(0) | コメント(0)
2023/01/08

ファイルをコピーする。

固定リンク | by:aramaki
ファイルをコピーする。
コピー先に同名ファイルがあれば置き換える
----------------------------------------------------------------------------
public static boolean copyFile(String srcPath,String destPath){
if(srcPath==null || srcPath.equals("")) {
return false;

}
if(destPath==null || destPath.equals("")) {
return false;

}
try {
// コピー先に同名ファイルがあれば、置き換え
Files.copy(Paths.get(srcPath), Paths.get(destPath), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}

return false;
}
22:57 | 投票する | 投票数(0) | コメント(0)
2023/01/05

Json基礎

固定リンク | by:aramaki
Json基礎
-------------
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonReadToString {

public static void main(String[] args) throws Exception {
String json = "{"
+ "\"created_at\":\"Thu Apr 06 15:24:15 +0000 2017\", "
+ "\"id\": 850006245121695744, "
+ "\"text\": \"ツイート\""
+ "}";

ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);

System.out.println(node.get("id").longValue()); // → 850006245121695744
System.out.println(node.get("text").textValue()); // → "ツイート"
System.out.println(node.get("created_at").textValue()); // → "Thu Apr 06 15:24:15 +0000 2017"
}

}
08:37 | 投票する | 投票数(0) | コメント(0)
2023/01/04

画像ファイルのコピー

固定リンク | by:aramaki
画像ファイルのコピー
------------------------------------
public class FileCopyTest {

private static String inPath = "D:/temp/test.jpg";

private static String outPath = "D:/temp/out.jpg";

public static void main(String[] args) {
try {
copy(inPath,outPath);
} catch (IOException e) {
System.out.println("エラー");
e.printStackTrace();
}

}
// バイナリファイルのコピー
private static void copy(String inPath,String outPath) throws IOException {
DataInputStream dataInStream = new DataInputStream(
new BufferedInputStream(
new FileInputStream(inPath)));
DataOutputStream dataOutStream = 
new DataOutputStream(
  new BufferedOutputStream(
    new FileOutputStream(outPath)));
int readByte=0;
int totalByte=0;
byte[] b=new byte[2048];
while(-1 != (readByte = dataInStream.read(b))){
dataOutStream.write(b, 0, readByte);
totalByte += readByte;
System.out.println("Read: " + readByte + " Total: " + totalByte);
}
dataInStream.close();
dataOutStream.close();
}
}
23:46 | 投票する | 投票数(0) | コメント(0)
2022/12/18

読みこんだファイルの文字列をbyte配列データで返す

固定リンク | by:aramaki
 読みこんだファイルの文字列をbyte配列データで返す
--------------------------------------------------------------------------------
private static byte[] readFileToByte2(String filePath) throws Exception {
FileInputStream fileInputStream = new FileInputStream(filePath);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
ByteArrayOutputStream out = new ByteArrayOutputStream();

int s;
// 1バイトずつ読み込む
while ((s = bufferedInputStream.read()) != -1) {
// 読み込んだデータをバイト配列に格納する
out.write(s);
}

byte[] tmp=out.toByteArray();

fileInputStream.close();
out.close();
return tmp;
}
18:37 | 投票する | 投票数(0) | コメント(0)
2022/12/17

PreparedStatement addBatch

固定リンク | by:aramaki
PreparedStatement addBatch
----------------------------------------------
public class AddBatchTest {

private static final String URL = "jdbc:oracle:thin:@192.168.11.123:1521/pdborcl2";
private static final String username = "pdbadmin";
private static final String password = "aramaki3$$";
private static Connection connection = null;

public static void main(String[] args) {
PreparedStatement preparedStatement = null;
try {
createConnection();
connection.setAutoCommit(false);
String sql = "insert into MEMO(memo) values(?)";
preparedStatement = connection.prepareStatement(sql);
int num=1;
for (int i = 0; i < 30; i++) {
preparedStatement.setString(1, "メモ" + num);
preparedStatement.addBatch();
if(num % 10 == 0 || num == 30) {
preparedStatement.executeBatch();
}
num++;
}
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
if(preparedStatement!=null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

public static void createConnection() throws SQLException {
connection = DriverManager.getConnection(URL, username, password);
}

}
23:07 | 投票する | 投票数(0) | コメント(0)
2022/11/27

VBScriptでCSVファイル読み込み

固定リンク | by:aramaki
VBScriptでCSVファイル読み込み
---------------------------------------------
Dim objFso As Object
Dim filePath
Dim objFile As Object
Dim aryRet()
Dim i
Dim objWshShell As Object

Dim ret_splited


Dim j As Integer
Dim k As Integer

Dim objXls
Dim objSheet

Set objFso = CreateObject("Scripting.FileSystemObject")

Set objWshShell = CreateObject("WScript.Shell")

filePath = "E:\temp\out1.csv"  


'Set objFile = objFso.OpenTextFile(objWshShell.CurrentDirectory & filePath )
'ファイルを読み取り専用で開く
Set objFile = objFso.OpenTextFile(filePath, 1, False)

If Err.Number = 0 Then
'ループカウンター初期化
i = 0

'ファイルを1行づつ配列に格納
Do Until objFile.AtEndOfStream

    '中身を保ったまま配列の大きさを拡張
    ReDim Preserve aryRet(i)

    '1行読み込んで配列に格納
    aryRet(i) = objFile.readLine

    If i = 1 Then
        ret_splited = Split(aryRet(i), ",")
    End If

    'カウンター増加
    i = i + 1

 Loop

'ファイルクローズ
objFile.Close
Set objFile = Nothing
Set objFso = Nothing

Else

'エラー内容
WScript.Echo "ファイルが開けません : " & Err.Description

End If
20:12 | 投票する | 投票数(0) | コメント(0)
2022/11/23

VBAパーツ(印刷)

固定リンク | by:aramaki
VBAパーツ(印刷)
----------------------
  ActiveSheet.HPageBreaks.Add Before:=Cells(i, 1) '垂直な改ページを挿入したい左側のセルを指定

With ActiveSheet.PageSetup
        .PrintTitleRows = "$1:$2"
        .PrintArea = "A1:D" & er
        .TopMargin = Application.CentimetersToPoints(3)
        .RightFooter = "&P/&N"
        .PaperSize = xlPaperA4
        .Orientation = xlPortrait
        .Zoom = 120
    End With

ActiveSheet.PrintPreview '印刷プレビュー
13:01 | 投票する | 投票数(0) | コメント(0)
123456
Copyright © Java活用生活 All Rights Reserved .