Javaでファイルダウンロード
Javaでファイルをダウンロードする方法について調査した。
ファイルをBufferedInputStreamにし、viewへのリターン時にアノテーションでパラメータとして設定する。
以下Struts2を使用した実装例。
@Result(name="success", value = "inputStream", params = { "inputName", "inputStream", "contentType", "application/octet-stream; charset=UTF-8", "contentLength", "${contentLength}", "contentDisposition", "attachment; filename=${fileName}" }, type = StreamResult.class) public class DownloadAtion { /** ファイルダウンロード用InputStream */ private InputStream inputStream; /** ダウンロードファイル名 */ private String fileName; /** ダウンロードファイルサイズ */ private long contentLength; public String download() throws Exception { String sampleFilePath = "/usr/local/files/test.txt"; File downloadFile = new File(sampleFilePath); // ファイルが存在し、ディレクトリで場合にダウンロードを行う。 if (downloadFile.exists() && !downloadFile.isDirectory()) { try { // ダウンロード用にinputStream化する。 inputStream = new BufferedInputStream(new FileInputStream(sampleFilePath)); // ファイル名 fileName = URLEncoder.encode(downloadFile.getName(), "UTF-8");fileName = URLEncoder.encode(downloadFile.getName(), "UTF-8"); // ファイルのバイト数 contentLength = downloadFile.length(); return "success"; } catch (Exception e) { return "error"; } } // ファイルが存在しないか、パスがファイルでない場合はエラーを返す。 return "error"; } /** * ファイルダウンロード用InputStreamを取得します。 * @return ファイルダウンロード用InputStream */ public InputStream getInputStream() { return inputStream; } /** * ファイルダウンロード用InputStreamを設定します。 * @param inputStream ファイルダウンロード用InputStream */ public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } /** * ダウンロードファイル名を取得します。 * @return ダウンロードファイル名 */ public String getFileName() { return fileName; } /** * ダウンロードファイル名を設定します。 * @param fileName ダウンロードファイル名 */ public void setFileName(String fileName) { this.fileName = fileName; } /** * ダウンロードファイルサイズを取得します。 * @return ダウンロードファイルサイズ */ public long getContentLength() { return contentLength; } /** * ダウンロードファイルサイズを設定します。 * @param contentLength ダウンロードファイルサイズ */ public void setContentLength(long contentLength) { this.contentLength = contentLength; } }
Javaでのファイルの存在チェック
File.exists()がよさげ。
// 同名のファイルが存在する場合はシステム日付をファイル名に付与 File file = new File(uploadDir + uploadFileName); if (file.exists()){ System.out.print("ファイルあるよー"); }
Javaでのファイルアップロード
Javaでファイルアップロードを実装する方法を調べた。
FileUtilsのcopyFileが使い勝手が良さそう。
*画面側
<input type="file" name="inputFile />
*Java側
public String upload() throws Exception { // ファイルアップロードのテスト String destPath = "/usr/local/tomcat/webapps/upload"; String myFileFileName = "uploadFile"; try{ File destFile = new File(destPath, myFileFileName); FileUtils.copyFile(getInputFile(), destFile); }catch(IOException e){ e.printStackTrace(); return ERROR; } } /** * 取込ファイルを取得 * @return 取込ファイル */ public File getInputFile() { return inputFile; } /** * 取込ファイルを設定 * @return 取込ファイル */ public void setInputFile(File inputFile) { this.inputFile = inputFile; }
macでAlt + PrintScreen的なことをした(アクティブなウィンドウのキャプチャ)
command + shift + 4 押下後にspaceキー押下でアクティブなウィンドウのみのキャプチャができる。
Javaでバイト数での空白埋め
空白埋めにはString.format("%10s", value)を使用すれば良いが、
String.format()はマルチバイトも1文字として認識するため、
固定長ファイル出力など、バイト数での空白埋めをするには個別で実装する必要がある。
以下文字をSJISとして扱った場合の空白埋め
public class Test{ public static void main(String []args){ String value = "テスト"; value = fillUpSpace(value, 10); System.out.println(value); //"テスト "として出力される。 } public static String fillUpSpace(String val, int num) { String fillUppedString = val; int len = 0; try { // SJISでのサイズ取得 len = val.getBytes("sjis").length; if (num <= len) { // 引数の桁より少ない場合は引数の桁に切り捨てる fillUppedString = new String(val.getBytes("sjis"), 0, num, "sjis"); } else { for(int i = 0 ; i < (num - len); i++) { fillUppedString = fillUppedString + " "; } } } catch(Exception e) { return ""; } return fillUppedString; } }
OutputStream から InputStream への変換
// baosの生成 ByteArrayOutputStream baos = new ByteArrayOutputStream(); // baosへの書込 baos.write(・・・); ・・・ // baosのからbaisへの変換 bais = new ByteArrayInputStream(baos.toByteArray());
Javaで文字コードを指定したファイル出力
文字コードを指定してファイル出力する際は、OutputStreamWriterを使用する。
import java.io.FileOutputStream; import java.io.OutputStreamWriter; public void outputFile() { FileOutputStream outputStream = null; OutputStreamWriter outputStreamWriter = null; try { outputStream = new FileOutputStream("ファイル名.txt"); // エンコード // EUC-JPやUTF-8など outputStreamWriter = new OutputStreamWriter(outputStream, "SJIS"); // 改行されないので改行コードをいれる outputStreamWriter.write("1行目\n"); outputStreamWriter.write("2行目\n"); outputStreamWriter.close(); } catch (UnsupportedEncodingException e) { System.out.print(e); } catch (IOException e) { System.out.print(e); } finally { if (outputStreamWriter != null) { outputStreamWriter.close(); } if (outputStream != null) { outputStream(); } } }