Java活用生活

ログイン

オンライン状況

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

カウンタ

COUNTER363160

日誌

MyDoc(備忘録)
123456
2025/04/20

ファイル読み込み

固定リンク | by:aramaki
ファイル読み込み
-------------------------
@PostMapping("/rest/json")
public String recieveJson(@RequestBody Info info) {


String res=null;
try(
// out.jsonファイルを読み込み、読み込んだデータをresponseとして返す。
FileReader fileReader=new FileReader("C:/out.json");
BufferedReader bufferedReader=new BufferedReader(fileReader)
) {
// out.jsonファイルを読み込み、読み込んだデータをresponseとして返す。
String line=null;
StringBuilder stringBuffer=new StringBuilder();
while((line=bufferedReader.readLine())!=null) {
stringBuffer.append(line);
}
res=stringBuffer.toString();

return res;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
//String res="{\"resultMessage\":\"OK\"}";
return null;
22:35 | 投票する | 投票数(0) | コメント(0)
2025/04/20

指定した位置から文字列取得

固定リンク | by:aramaki
指定した位置から先の文字を取得する
--------------------------------------------------
public static String getRightString(String strData,int index) {
// 切り出し結果
String result=null;
if(null==strData || strData.length()==0) {
// 切り出し対象文字列がnull、または、空文字の場合、nullを返却する。
return result;
}
if(index > strData.length()-1) {
return result;
}
result=strData.substring(index);
return result;
}
10:48 | 投票する | 投票数(0) | コメント(0)
2025/04/20

文字のきりだしNO2

固定リンク | by:aramaki
文字列の先頭から指定した桁数切り出す。
----------------------------------------------------------
public static String getLeftString(String strData,int index) {
String result=null;
if(null==strData || strData.length()==0) {
// 切り出し対象文字列がnull、または、空文字の場合、nullを返却する。
return result;
}
if(index > strData.length()) {
return result;
}
if(strData.length()>0) {
result=strData.substring(0,index);
}
return result;
}
10:26 | 投票する | 投票数(0) | コメント(0)
2025/04/19

文字列の先頭から指定した桁数切り出す

固定リンク | by:aramaki
文字列の先頭から指定した桁数切り出す
------------------------------------------------------
/**
* 文字列の先頭から指定した桁数切り出す。
* @param strData
* @param index
* @return
*/
public static String getLeftString(String strData,int index) {
String result=null;
if(index > strData.length()) {
return result;
}
if(null!=strData && strData.length()>0) {
result=strData.substring(0,index);
}
return result;
}
22:11 | 投票する | 投票数(0) | コメント(0)
2025/04/16

日時データ部品

固定リンク | by:aramaki
日時データ部品
-----------------------
public class DateTime {
private static SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

private static List<Calendar> calList=new LinkedList<Calendar>();
public static void main(String[] args) {
// 年度開始日と終了日
/*
List<String> list=getYearRange(2025);
for(String date : list) {
System.out.println(date);
}
*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
 
Calendar startCal= makeStartCalender(2025);
System.out.println(sdf.format(startCal.getTime()));
calList.add(startCal);
while(true) {
Calendar cal=getNext30Minite(startCal,30);
System.out.println(sdf.format(cal.getTime()));
int diff=startCal.compareTo(cal);
if(diff==0) {
// startCalとcalが同じ日時
break;
}
calList.add(cal);
}
for(Calendar cal: calList) {
// 日付出力する
String strDate=dateFormat.format(cal);
System.out.println(strDate);
}

}
public static Calendar makeStartCalender(int startYear) {
// 指定した年の4月1日
// 2025年の4月1日の場合
Calendar calendar=Calendar.getInstance();
calendar.set(startYear,3,1,0,0,0);
return calendar;
}
public static Calendar makeEndDate(int year) {
Calendar calendar=Calendar.getInstance();
calendar.set(year+1, 2,31,11,59,30);
return calendar;
}
public static Calendar getNext30Minite(Calendar calendar,int addMinite) {
calendar.add(Calendar.MINUTE, addMinite);
return calendar;
}
23:49 | 投票する | 投票数(0) | コメント(0)
2025/04/16

年度の開始日と終了日を取得する

固定リンク | by:aramaki
年度の開始日と終了日を取得する
----------------------------------------------------
public static List<String> getYearRange(int year) {
List<String> list=new ArrayList<String>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
LocalDateTime startOfYear=LocalDateTime.of(year, Month.APRIL, 1,0,0);
LocalDateTime endOfYear=LocalDateTime.of(year+1, Month.MARCH, 31,0,0);
String strStartOfYear= startOfYear.format(formatter);
String strEndOfYear= endOfYear.format(formatter);
list.add(strStartOfYear);
list.add(strEndOfYear);
return list;
}
22:06 | 投票する | 投票数(0) | コメント(0)
2025/04/13

JSON取得でExecutorService

固定リンク | by:aramaki
JSON取得でExecutorService
------------------------------------------------
ここで使うべきか検討必要
public void readForPostJson(String urlPath) throws Exception{
 
    ExecutorService executor = Executors.newFixedThreadPool(3);//CPUコア数4として最適なプール数
   try {
    URI uri=new URI(urlPath);
URL url=uri.toURL();
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.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// ---------------------
// 接続を確率
// ---------------------
connection.connect();
// JSONデータを出力ストリームへ書き出すデータ
Info info=new Info();


ObjectMapper mapper=new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
String strJson=mapper.writeValueAsString(info);
PrintStream printStream=new PrintStream(connection.getOutputStream());
printStream.print(strJson);
printStream.close();
// jsonデータを出力ストリームへ書き出す
/*
BufferedWriter writer
=new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));
writer.write(strJson);
writer.close();
*/
// レスポンスコードを取得する。
int responseCode=connection.getResponseCode();
log.info("responseCode =" +responseCode);
// 接続が正常かステータスコードを取得する。
if(HttpURLConnection.HTTP_OK==responseCode) {

// JSONテキストを取得する。
//StringBuffer stringBuffer=new StringBuffer();
// JSONデータ取得
InputStream inputStream=connection.getInputStream();

Future<Boolean> future=executor.submit(new Callable<Boolean>() {

@Override
public Boolean call() throws Exception {
Boolean res=false;
res=processLargeJson(inputStream);
return res;
}
});
Boolean result=future.get();
log.info("Boolean bool= :::"+result.booleanValue());
Thread.sleep(1000);
 
//processLargeJson(inputStream);
}
}finally {
if(executor!=null){
executor.shutdown(); 
}
}
}

21:00 | 投票する | 投票数(0) | コメント(0)
2025/04/13

JSONメモ②

固定リンク | by:aramaki
JSONメモ②
----------------------------------------
/**
 * 
 * リモートサーバーからJSONを取得するsample
 */
@Service
@Slf4j
public class JsonService {
public static final String JSON_URL ="https://sample.com/out.json";
//JsonデータPost先URL
public static final String PATH="http://localhost:8080/rest/json";
public void readJsonStr() {
readOutJson(JSON_URL);
}
//Rest送信コール
// JSONデータ(Info.java→info.json)をRestを利用し、リクエストBodyにセットして送信し、
// WebAPIから返却されるJsonデータを取得して、Javaのオブジェクトへ変換する。
public void postJsonData() throws Exception{
readForPostJson(PATH);
}
public void readForPostJson(String urlPath) throws Exception{
URI uri=new URI(urlPath);
URL url=uri.toURL();
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.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// ---------------------
// 接続を確率
// ---------------------
connection.connect();
// JSONデータを出力ストリームへ書き出すデータ
Info info=new Info();


ObjectMapper mapper=new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
String strJson=mapper.writeValueAsString(info);
PrintStream printStream=new PrintStream(connection.getOutputStream());
printStream.print(strJson);
printStream.close();
// jsonデータを出力ストリームへ書き出す
/*
BufferedWriter writer
=new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));
writer.write(strJson);
writer.close();
*/
// レスポンスコードを取得する。
int responseCode=connection.getResponseCode();
log.info("responseCode =" +responseCode);
// 接続が正常かステータスコードを取得する。
if(HttpURLConnection.HTTP_OK==responseCode) {

// JSONテキストを取得する。
//StringBuffer stringBuffer=new StringBuffer();
// JSONデータ取得
InputStream inputStream=connection.getInputStream();

processLargeJson(inputStream);
}
}


/**
* リモートサーバーにあるJSONファイルからJSON文字列を取得する。
* @param urlPath リモートサーバーのJSONファイルパス
* @return
*/
public void readOutJson(String urlPath) {
try {
URI uri=new URI(urlPath);
URL url=uri.toURL();
// 接続オブジェクトを取得する。
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
// リクエストメソッドを取得
connection.setRequestMethod("GET");
// 通信開始
connection.connect();
// レスポンスコードを取得する。
int responseCode=connection.getResponseCode();
// 接続が正常かステータスコードを取得する。
if(HttpURLConnection.HTTP_OK==responseCode) {
// エンコード取得
String encoding=connection.getContentEncoding();
if(null==encoding) {
encoding="UTF-8";
}
// JSONデータ取得
InputStream inputStream=connection.getInputStream();
/*********************************
try(
InputStream inputStream=connection.getInputStream();
InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);){
String line=null;
StringBuilder stringBuffer=new StringBuilder();
while((line=bufferedReader.readLine())!=null) {
stringBuffer.append(line);
}
System.out.println(stringBuffer.toString());
//取得した文字列を返す
//return stringBuffer.toString();
}catch (Exception e) {
log.error("JSON取得処理に失敗しました。");
e.printStackTrace();
}
/***********************************/
processLargeJson(inputStream);
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void processLargeJson(InputStream inputStream) throws IOException{
JsonFactory jsonFactory=new JsonFactory();
// JSON解析オブジェクト生成
//JsonParser jsonParser=jsonFactory.createParser(new BufferedInputStream(inputStream, 2048));
// -----------------------------------------------------------------
// InputStreamの利点が入力を少しずつ読み取ることができるという理由で、
// JSON全体をメモリにプルしても問題ないことを前提としています.
// https://stackoverflow.com/questions/6511880/how-to-parse-a-json-input-stream
// -----------------------------------------------------------------
JsonParser jsonParser=jsonFactory.createParser(inputStream);
// --------------------------
// トークンストリームの処理
// ---------------------------
// -- info を取得する。--
int cnt=0;
while (jsonParser.nextToken()!=JsonToken.END_OBJECT) {
String fieldName=jsonParser.currentName();
log.info("fieldName="+fieldName);
// infoの内容を取得する。
if("info".equals(fieldName)) {
processFieldElement(jsonParser);
}
// dataの内容を取得する。
if("data".equals(fieldName)) {
processResultFieldElement(jsonParser);
}
}
inputStream.close();
jsonParser.close();
System.out.println("END");
}
    /**
     * infoのデータを取得する。
     * @param jsonParser
     * @throws IOException
     */
public void processFieldElement(JsonParser jsonParser) throws IOException{
JsonToken jsonToken=jsonParser.nextToken();
if(jsonToken==JsonToken.START_OBJECT) {
ObjectMapper mapper=new ObjectMapper();
JsonNode node=mapper.readTree(jsonParser);
String strInfoNde=mapper.writeValueAsString(node);
System.out.println("strInfoNde="+strInfoNde);
}
}
/**
* dataのデータを取得する。
* @param jsonParser
* @throws IOException
*/
public void processResultFieldElement(JsonParser jsonParser) throws IOException{
JsonToken jsonToken=jsonParser.nextToken();
if(jsonToken==JsonToken.START_OBJECT) {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonParser);
String dayTimeJson=mapper.writeValueAsString(node);

System.out.println("strNode="+dayTimeJson);
TypeReference<Map<String,List<String[]>>> typeRef
=new TypeReference<Map<String,List<String[]>>>() {}; 
Map<String,List<String[]>> mapData=mapper.readValue(dayTimeJson, typeRef);
// Mapデータの中身を表示する。
Set<String> keys= mapData.keySet();
Iterator<String> itr=keys.iterator();
while(itr.hasNext()) {
String setsubiCode=itr.next();
List<String[]> dataList=mapData.get(setsubiCode);
for(int i=0;i<dataList.size();i++) {
String[] data=dataList.get(i);
for(int j=0;j<data.length;j++) {
String str=data[i];
System.out.print(str+" ");
}
System.out.println();
}
}
System.out.println("TEST");
}
}
}

17:16 | 投票する | 投票数(0) | コメント(0)
2025/04/11

半角数字チェック参考サイト

固定リンク | by:aramaki
07:36 | 投票する | 投票数(0) | コメント(0)
2025/04/07

備忘録

固定リンク | 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;
}


●閏年判定 ****************
閏年判定
-----------
import java.util.Calendar;

public class UruuHantei {

public static void main(String[] args) {
boolean bool=checkLeapYear(2020);
System.err.println("bool = " + bool);

}
private static boolean checkLeapYear(int targetYear) {
Calendar calendar=Calendar.getInstance();
calendar.set(targetYear, Calendar.FEBRUARY,1);
// 2月の最終日(最大日)
int maxDay=calendar.getActualMaximum(Calendar.DATE);
System.out.println("maxDay = " +maxDay);
if(maxDay==29) {
return true;
}
return false;
}

}

実行結果
-------------
bool = true
maxDay = 29
*********************************


※************* 指定ディレクトリーのJSONファイル名取得 *********
public static List<File> getFileListInDir(String destDir) {
  List<File> fileList=new ArrayList<>();
  //ディレクトリ情報取得インターフェイス
  File outDir=new File(destDir);
  //ファイル一覧取得
  File[] files=outDir.listFiles();
  for(File file : files) {
   if(file.isFile() && file.getName().endsWith(".json")) {
    //ファイルで、末尾が「.json」のファイルをListに追加
    fileList.add(file);
   }
  }
  return fileList;
 }

※************* クラスパスを通した設定ファイルを読み込む *********
-------------------------------------------------------------------
InputStream inputStream=Main.class.getResourceAsStream("/client.properties");

Properties properties=new Properties();
try {
properties.load(inputStream);
inputStream.close();
System.out.println("send.server.port =" + properties.getProperty("send.server.port"));
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}


Workbook workbook = WorkbookFactory.create();
Sheet sheet = workbook.createSheet("Sample Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("中央揃え");

// セルスタイルを作成
CellStyle style = workbook.createCellStyle();
// 縦方向を中央揃えに設定
style.setVerticalAlignment(VerticalAlignment.CENTER);

● フォントタブでフォント名、スタイル、サイズ等をセットする
Font font = workbook.createFont();
font.setFontName("Arial");  // フォント名
font.setFontHeightInPoints((short) 12);  // フォントサイズ
font.setBold(true);  // 太字に設定
font.setItalic(false);  // 斜体を無効化

// セルスタイルにフォントを適用
style.setFont(font);

●罫線で線をセットする
// 上、下、左、右の罫線を設定
style.setBorderTop(BorderStyle.THIN);  // 上の罫線
style.setBorderBottom(BorderStyle.THIN);  // 下の罫線
style.setBorderLeft(BorderStyle.THIN);  // 左の罫線
style.setBorderRight(BorderStyle.THIN);  // 右の罫線

// 罫線の色を設定
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
style.setRightBorderColor(IndexedColors.BLACK.getIndex());

●Excelスタイルサンプル
public class App {
    public static void main(String[] args) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Sample Sheet");
            Row row = sheet.createRow(0);
            Cell cell = row.createCell(0);
            cell.setCellValue("フォーマット済みセル");

            // セルスタイルを作成
            CellStyle style = workbook.createCellStyle();

            // 縦方向中央揃え
            style.setVerticalAlignment(VerticalAlignment.CENTER);

            // フォント設定
            Font font = workbook.createFont();
            font.setFontName("Arial");
            font.setFontHeightInPoints((short) 12);
            font.setBold(true);
            style.setFont(font);

            // 罫線設定
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
            style.setTopBorderColor(IndexedColors.BLACK.getIndex());
            style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
            style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
            style.setRightBorderColor(IndexedColors.BLACK.getIndex());

            // スタイルをセルに適用
            cell.setCellStyle(style);

            // ファイル出力
            try (FileOutputStream fos = new FileOutputStream("formatted_excel.xlsx")) {
                workbook.write(fos);
            }

            System.out.println("エクセルファイルが生成されました。");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
22:37 | 投票する | 投票数(0) | コメント(0)
123456
Copyright © Java活用生活 All Rights Reserved .