Search

'File'에 해당되는 글 4건

  1. 2013.12.11 Java - File Hash 값 추출
  2. 2012.07.31 Spring 파일 업로드
  3. 2010.04.04 Delphi Tip - 디렉토리 문자열 분리
  4. 2009.05.12 [Delphi] - File

Java - File Hash 값 추출

Programming/Java 2013.12.11 09:56 Posted by 파란크리스마스

DigestUtils

package bluexmas.utils;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DigestUtils {

	public static String extractStringHashSHA256(String str){
		String SHA = ""; 
		try{
			MessageDigest sh = MessageDigest.getInstance("SHA-256"); 
			sh.update(str.getBytes()); 
			byte byteData[] = sh.digest();
			StringBuffer sb = new StringBuffer(); 
			for(int i = 0 ; i < byteData.length ; i++){
				sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
			}
			SHA = sb.toString();
			
		}catch(NoSuchAlgorithmException e){
			e.printStackTrace(); 
			SHA = null; 
		}
		return SHA;
	}
	
	public static String extractFileHashSHA256(String filename) throws Exception {
		
		String SHA = ""; 
		int buff = 16384;
		try {
			RandomAccessFile file = new RandomAccessFile(filename, "r");

			MessageDigest hashSum = MessageDigest.getInstance("SHA-256");

			byte[] buffer = new byte[buff];
			byte[] partialHash = null;

			long read = 0;

			// calculate the hash of the hole file for the test
			long offset = file.length();
			int unitsize;
			while (read < offset) {
				unitsize = (int) (((offset - read) >= buff) ? buff : (offset - read));
				file.read(buffer, 0, unitsize);

				hashSum.update(buffer, 0, unitsize);

				read += unitsize;
			}

			file.close();
			partialHash = new byte[hashSum.getDigestLength()];
			partialHash = hashSum.digest();
			
			StringBuffer sb = new StringBuffer(); 
			for(int i = 0 ; i < partialHash.length ; i++){
				sb.append(Integer.toString((partialHash[i]&0xff) + 0x100, 16).substring(1));
			}
			SHA = sb.toString();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		return SHA;
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(extractStringHashSHA256("1"));
		System.out.println(extractFileHashSHA256("a.pdf"));
	}	
}


신고

Spring 파일 업로드

Programming/Java 2012.07.31 15:44 Posted by 파란크리스마스

Spring Controller

@Controller
@RequestMapping(value = "/form/mfile_add")
public class CMXFileAddController {

	@RequestMapping(method = RequestMethod.GET)
	public String getUploadForm(Model model) {
		MFile mFile = new MFile ();
		model.addAttribute("mFile", mFile);
		return "/form/mfile_add";
	}

mfile_add.jsp

<form:form modelAttribute="mFile" method="post" enctype="multipart/form-data">

        <legend>자료 등록</legend>

        <table>
          <TR>
            <TD><form:label for="title" path="title">제목</form:label></TD>
            <TD><form:input path="title" type="text" size="85"/></TD>
          </TR>
          <TR>
            <TD><form:label for="file1" path="file1">파일1</form:label></TD>
            <TD><form:input path="file1" type="file" size="70"/></TD>
          </TR>
          <TR>
            <TD><form:label for="desc" path="desc">설명</form:label></TD>
            <TD><form:textarea path="desc" cols="84" rows="5" /></TD>
          </TR>
        </table>

        <input type="submit" value="등록"/>

</form:form>

Post 파일 업로드 처리

	@RequestMapping(method = RequestMethod.POST)
	public String create(MFile mFile, BindingResult result) {
		
		System.out.println(mFile);
		
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
			}
			return "/form/mfile_add";
		}

		if (!mFile.getFile1().isEmpty()) {
			String filename = mFile.getFile1().getOriginalFilename();
			String imgExt = filename.substring(filename.lastIndexOf(".") + 1, filename.length());

			// upload 가능한 파일 타입 지정
			if (imgExt.equalsIgnoreCase("xls")) {
				byte[] bytes = mFile.getFile1().getBytes();
				try {
					File lOutFile = new File(fsResource.getPath() + filename  + "_temp.xls");
					FileOutputStream lFileOutputStream = new FileOutputStream(lOutFile);
					lFileOutputStream.write(bytes);
					lFileOutputStream.close();
				} catch (IOException ie) {
					// Exception 처리
					System.err.println("File writing error! ");
				}
				System.err.println("File upload success! ");
			} else {
				System.err.println("File type error! ");
			}
		
		}
		return "redirect:mfile_list.itg";
	}

 

신고

Delphi Tip - 디렉토리 문자열 분리

Programming/Delphi 2010.04.04 06:31 Posted by 파란크리스마스


uses
  StrUtils;

procedure TForm1.Button1Click(Sender: TObject);
var
  tmpDirStr : String;
  offset : integer;

  function GetFindStr(SubFindStr : String; var offset : integer):string;
  var
    offsetOld, offset2 : integer;
  begin
    Result := '';

    offset2 := 0;
    if SubFindStr[offset] = '/' then
      inc(offset2);

    offsetOld := offset;
    offset := PosEx('/', SubFindStr, offset + offset2);

    if offset>0 then begin
      Result := MidStr(SubFindStr, offsetOld + offset2, offset-offsetOld-offset2);
    end;
  end;

begin
  tmpDirStr := Edit1.Text;

  if (tmpDirStr[Length(tmpDirStr)]<>'/') then
    tmpDirStr := tmpDirStr + '/';

  offset := 1;

  while (offset > 0) do begin
    Memo1.Lines.Add(GetFindStr(tmpDirStr, offset));
  end;
end;

신고

[Delphi] - File

Programming/Delphi 2009.05.12 15:08 Posted by 파란크리스마스

FileCopy

출처 : http://delphi.about.com/od/fileio/a/untypedfiles.htm

procedure FileCopy(const FileFrom, FileTo: string) ;
var
  FromF, ToF: file;
  NumRead, NumWritten: Integer;
  Buffer: array[1..2048] of Byte;
begin
  AssignFile(FromF, FileFrom) ;
  Reset(FromF, 1) ;
  AssignFile(ToF, FileTo) ;
  Rewrite(ToF, 1) ;
  repeat

   BlockRead(FromF, Buffer, SizeOf(Buffer), NumRead) ;
   BlockWrite(ToF, Buffer, NumRead, NumWritten) ;
  until (NumRead = 0) or (NumWritten <> NumRead) ;
  CloseFile(FromF) ;
  CloseFile(ToF) ;
end;

Random access file

출처 : http://www.tek-tips.com/viewthread.cfm?qid=1540019&page=3

type
  recordtype=record
    varLastName   :string[50];
    varFirstName  :string[50];
    varEmail     :string[250];
end;

  qfile:file of recordtype;
  qfileTemp:file of recordtype;
  qrecord:recordtype;
  numrec:integer;
  numtemp:integer;

procedure TfrmDataBase.imgDeleteMouseUp(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin

  try

    ASSIGNFILE(qfile, Trim(lblFile.Caption));
    Reset(qfile);

    ASSIGNFILE(qfiletemp, ExtractFilePath(application.exename) + '\Database.tmp');
    REWRITE(qfiletemp);

      For numtemp:=0 To filesize(qfile)-1 Do
        begin

          seek(qfile,numtemp);
          read(qfile,qrecord);

          If IntToStr(numtemp + 1) <> Trim(lblPosition.Caption)  Then
            begin
              write (qfiletemp, qrecord);
            end;

        end;

    closefile(qfile);
    closefile(qfiletemp);

    deletefile(Trim(lblFile.Caption));
    renamefile(ExtractFilePath(application.exename) + '\Database.tmp', Trim(lblFile.Caption));

  except
   ShowMessage('Warning: access to file has been denied.' + #10 + #13 + #10 + #13 + 'Make sure the application folder is not read-only.');
   exit;
  end;

end;

신고
TAG Delphi, File


 

티스토리 툴바