Javaのメモ

ファイルの削除

ファイルの確認と削除 - ファイルを管理する - Java入門

class fileTest8{ public static void main(String args[]){ File file = new File("c:¥¥tmp¥¥newfile.txt");

if (file.exists()){
  if (file.delete()){
    System.out.println("ファイルを削除しました");
  }else{
    System.out.println("ファイルの削除に失敗しました");
  }
}else{
  System.out.println("ファイルが見つかりません");
}

}

ファイルパスからディレクトリを取得する

【Java】ファイルパスからディレクトリを取得する - オープンリファレンス

    String dirName = new File("c:\\temp\\sample\\test.txt").getParent();
    System.out.println(dirName);

JavaでSSH - どすこいにがうり君の細マッチョ伝説

String hostname = "192.168.0.1"; // 接続先 String userid = "user"; // ユーザ名 String password = "pass"; // パスワード int portNo = 22; // ポート番号 String serverPath = "/home/user1/"; // サーバのパス String localPath = "C:/hoge/"; // ローカルのパス

JSch jsch = new JSch();

// HostKey チェックを行わない Hashtable<String, String> config = new Hashtable<String, String>(); config.put("StrictHostKeyChecking", "no"); JSch.setConfig(config);

// 接続情報設定 Session session = jsch.getSession(userid, hostname, portNo); session.setPassword(password);

try { // 接続 session.connect(); } catch (JSchException e) { System.out.println("error."); return; }

// sftp ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); channel.connect();

// pwd System.out.println(channel.pwd());

// cd channel.cd(serverPath);

List fileList = new ArrayList();

// ls List<?> list = channel.ls("."); for (int i = 0; i < list.size(); ++i) { LsEntry entry = (LsEntry) list.get(i);

// ディレクトリやリンクは除外
SftpATTRS attr = entry.getAttrs();
if (attr.isDir() || attr.isLink()) {
    continue;
}

String fileName = entry.getFilename();
fileList.add(serverPath + "/" + fileName);

}

// サーバ上ファイル一覧(フルパス) for (String filePath : fileList) { System.out.println(filePath); }

// 以下、例として一番目のファイルを使用する

// ファイルを取得 InputStream input1 = channel.get(fileList.get(0));

// ローカルのファイルと比較 InputStream input2 = new FileInputStream(localPath + *1.getFilename()); boolean result = IOUtils.contentEquals(input1, input2); System.out.println(result);

if (!result) { // ファイルをローカルに保存 byte[] byteArr = IOUtils.toByteArray(input1); FileOutputStream fos = new FileOutputStream(localPath + *2.getFilename()); fos.write(byteArr); fos.close(); }

*1:LsEntry) list.get(0

*2:LsEntry) list.get(0