반응형

 

 

 

package kr.co.xxx;

import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;  
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 
 
import org.junit.Before;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult; 
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 

import org.json.simple.JSONObject;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DbserverApplication.class)
@WebAppConfiguration
public class DbserverApplicationTests {

Logger log = LoggerFactory.getLogger(DbserverApplication.class);
 
    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;

  

public void logPrint(String Name) {
log.info(" ");
log.info("=======================================================");
log.info(" ");

log.info(Name);

log.info(" ");
log.info("=======================================================");
log.info(" ");
}

public void endLogPrint() {
log.info(" ");
log.info("=======================================================");
log.info(" ");
}



    @Before 
    public void setUp() throws Exception {  
     logPrint("Set Up");
    
     // 이곳에서 DbserverController를 MockMvc 객체로 만듭니다.   
        
     mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();      
        
        endLogPrint();
         
        
         
    } 

    /*
    @Test
    public void testIsRunning() throws Exception { 
     logPrint("ISRunning");
    
     mockMvc.perform(get("/ping")
            )
     .andDo(print())                // 출력
     .andExpect(status().isOk());   // 정상 결과 예상
    
    
    
     endLogPrint();
    }
      
    

    
    @SuppressWarnings("unchecked")
@Test
    public void testGetVideoInfo() throws Exception { 
     log.info("GetVideoInfo");
    
     // 전체 JSON Object 담을 정보
     //JSONArray mapArray = new JSONArray();
    
     // 한개의 정보가 들어갈 JSONObject 선언
     JSONObject mapInfo = new JSONObject();
    
     // 정보 입력
     mapInfo.put("xmin", "-111.46727710962297");
     mapInfo.put("ymin", "20.462022433054965" );
     mapInfo.put("xmax", "-110.46727710962297");
     mapInfo.put("ymax", "21.96517113846002"  );
    
     // Array 값 추가
     //mapArray.add(mapInfo);  
        
     mockMvc.perform(post("/getVideoInfo") 
     .header("Accept", "application/json")
     .contentType("application/json")
     .characterEncoding("utf-8") 
     .content(mapInfo.toString()) 
     )
.andDo(print())                // 출력
.andExpect(status().isOk())    // 정상결과 예상 
                ;
         
    
     endLogPrint();
    }         
    
    */

    
    @Test
    public void testIsRunning() throws Exception { 
     logPrint("ISRunning");
    
     MvcResult result = this.mockMvc.perform(get("/ping")
                                )
                 //.andDo(print())                // 출력
        .andExpect(status().isOk())    // 정상 결과 예상
        .andReturn()
        ;   
    
    
     // 결과를 받는 String
     String content = result.getResponse().getContentAsString();
      
     // 예상 결과 
     // 첫문장 비교해서 오류 발생하면 문제가 있는 것임
     assertEquals("I'm Alive!", content ); 
    
     endLogPrint();
    }
      
    
    
    @SuppressWarnings({ "unchecked" })
@Test(timeout = 100000)   // Timeout 시간 설정 (단위 : milliseconds)
    public void testGetVideoInfo() throws Exception {
      
    
     log.info("GetVideoInfo");
    
     // 전체 JSON Object 담을 정보
     //JSONArray mapArray = new JSONArray();
    
     // 한개의 정보가 들어갈 JSONObject 선언
     JSONObject mapInfo = new JSONObject();
    
     // 정보 입력
     mapInfo.put("xmin", "-111.46727710962297");
     mapInfo.put("ymin", "20.462022433054965" );
     mapInfo.put("xmax", "-95.15257984399797" );
     mapInfo.put("ymax", "22.96517113846002"  );
    
     // Array 값 추가
     //mapArray.add(mapInfo);   
        
     MvcResult result = this.mockMvc.perform(post("/getVideoInfo")              
     .header("Accept", "application/json")
     .contentType("application/json")
     .characterEncoding("utf-8") 
     .content(mapInfo.toString()) 
     ) 
//.andDo(print())                // 출력 (결과가가 길면 출력을 생략하는 것이 좋음)
.andExpect(status().isOk())    // 정상결과 예상 
.andReturn()
                ;
    
     
     // 결과를 받는 String
     String content = result.getResponse().getContentAsString();
    
     // ,를 기준으로 첫번째 값만 받아옴
     String [] con_list = content.split(",");
    
     // 정상 반환 여부를 확인하기 위해 첫번째 값 별도로 재저장
     String [] first_con = con_list[0].split(":");
    
     //result.
     log.info("first_con[0]  : " + first_con[0]); 
    
     // 예상 결과 
     // 첫문장 비교해서 오류 발생하면 문제가 있는 것임
     assertEquals("[{\"video_sn\"", first_con[0] ); 
    
     endLogPrint();
    }         
 
    
} // end of Class

반응형
반응형


FTK Imager 이슈


스마트폰 속 개인정보, 삭제해도 쉽게 복원된다 : http://economy.hankooki.com/lpage/it/201407/e20140710145634117700.htm

AccessData의 Forensic 이미징 도구 : FTK Imager 3.0 : http://solatech.tistory.com/208


위 블로그에 자세한 사항을 찾고하면 되겠다 ^^(포렌식 관련)


난 그중 위의 파일 복구 관련하여 한번 살펴보았다... 속도도 빠르고 검색 능력도 뛰어남....


다운로드 : http://www.accessdata.com/support/product-downloads

https://accessdata.com/product-download

2019.03.27 기준 : 4.2.1 버전이 최신 버전이며 이메일로 다운로드 주소가 보내집니다.



3.1.1 버전을 다운로드 받아 실행함 (일반적인 설치과정이라 별 다를게 없음...)


파일 복구 간단한 사용법...


설치 -> FTK Imager 실행 


1. 특정 드라이브 연결

   - File -> Add Evidence Item... 선택 -> Physical Driver (이동식 USB 연결) -> 60 여 기가의 usb 연결 선택 -> 마침






2. 이동식 USB 연결된 파일의 목록이 좌측에 뜨고

    지워진 (X 표시가 뜬) 파일이나 폴더를 선택하여 마우스 우클릭시 Export Files... 선택하여 복원하면 끝






















 









반응형
반응형


1. 빠른 파일 검색


사이트 : http://www.voidtools.com/

프로그램명 : everything



Everything-1.2.1.371.exe





설치 후 실행 화면



TOOLS -> OPTIONS -> HTTP 탭


사용하는 포트 정보 설정 가능


TOOLS -> Start HTTP Server 를 통해 웹 서비스 가능


즉, 웹을 통해 찾을려는 파일등을 쉽게 검색 가능함





2. 파일 내용 검색


사이트 : http://astrogrep.sourceforge.net/

프로그램명 : Astrogrep



AstroGrep_v4.3.0.zip


: 정규 표현식 (. 표준 마이크로 소프트 닷넷 정규식 사용 - 빠른 참조 ) 
동시 여러 파일 형식 - 
- 재귀 디렉토리 검색 
- 위하고 검색 아래 식을 줄을 선택 "컨텍스트"기능 
- 가장 최근에 사용을 검색 경로에 대한 목록 
다소 다양한 인쇄 옵션 - 
- 당신의 선택의 편집기를 사용하여 파일을 열려면 두 번 클릭 
- 상점 가장 최근에 사용한 파일 이름 및 검색 식 
- 단어 단위 만 
- 구문 highlighing 

- 무료 및 오픈 소스의 무료


MS 계열에 정규식 표현 가능...




Regular Expression Language - Quick Reference

.NET Framework 4.5
85 out of 96 rated this helpful Rate this topic

A regular expression is a pattern that the regular expression engine attempts to match in input text. A pattern consists of one or more character literals, operators, or constructs. For a brief introduction, see .NET Framework Regular Expressions.

Each section in this quick reference lists a particular category of characters, operators, and constructs that you can use to define regular expressions:

The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes in Regular Expressions.

Escaped character

Description

Pattern

Matches

\a

Matches a bell character, \u0007.

\a

"\u0007" in "Error!" + '\u0007'

\b

In a character class, matches a backspace, \u0008.

[\b]{3,}

"\b\b\b\b" in "\b\b\b\b"

\t

Matches a tab, \u0009.

(\w+)\t

"item1\t", "item2\t" in "item1\titem2\t"

\r

Matches a carriage return, \u000D. (\r is not equivalent to the newline character, \n.)

\r\n(\w+)

"\r\nThese" in "\r\nThese are\ntwo lines."

\v

Matches a vertical tab, \u000B.

[\v]{2,}

"\v\v\v" in "\v\v\v"

\f

Matches a form feed, \u000C.

[\f]{2,}

"\f\f\f" in "\f\f\f"

\n

Matches a new line, \u000A.

\r\n(\w+)

"\r\nThese" in "\r\nThese are\ntwo lines."

\e

Matches an escape, \u001B.

\e

"\x001B" in "\x001B"

\ nnn

Uses octal representation to specify a character (nnn consists of two or three digits).

\w\040\w

"a b", "c d" in

"a bc d"

\x nn

Uses hexadecimal representation to specify a character (nn consists of exactly two digits).

\w\x20\w

"a b", "c d" in

"a bc d"

\c X

\c x

Matches the ASCII control character that is specified by X or x, where X or x is the letter of the control character.

\cC

"\x0003" in "\x0003" (Ctrl-C)

\u nnnn

Matches a Unicode character by using hexadecimal representation (exactly four digits, as represented by nnnn).

\w\u0020\w

"a b", "c d" in

"a bc d"

\

When followed by a character that is not recognized as an escaped character in this and other tables in this topic, matches that character. For example, \* is the same as \x2A, and \. is the same as \x2E. This allows the regular expression engine to disambiguate language elements (such as * or ?) and character literals (represented by \* or \?).

\d+[\+-x\*]\d+\d+[\+-x\*\d+

"2+2" and "3*9" in "(2+2) * 3*9"

Back to top

A character class matches any one of a set of characters. Character classes include the language elements listed in the following table. For more information, see Character Classes in Regular Expressions.

Character class

Description

Pattern

Matches

[ character_group ]

Matches any single character in character_group. By default, the match is case-sensitive.

[ae]

"a" in "gray"

"a", "e" in "lane"

[^ character_group ]

Negation: Matches any single character that is not in character_group. By default, characters in character_group are case-sensitive.

[^aei]

"r", "g", "n" in "reign"

[ first - last ]

Character range: Matches any single character in the range from first to last.

[A-Z]

"A", "B" in "AB123"

.

Wildcard: Matches any single character except \n.

To match a literal period character (. or \u002E), you must precede it with the escape character (\.).

a.e

"ave" in "nave"

"ate" in "water"

\p{ name }

Matches any single character in the Unicode general category or named block specified by name.

\p{Lu}

\p{IsCyrillic}

"C", "L" in "City Lights"

"Д", "Ж" in "ДЖem"

\P{ name }

Matches any single character that is not in the Unicode general category or named block specified by name.

\P{Lu}

\P{IsCyrillic}

"i", "t", "y" in "City"

"e", "m" in "ДЖem"

\w

Matches any word character.

\w

"I", "D", "A", "1", "3" in "ID A1.3"

\W

Matches any non-word character.

\W

" ", "." in "ID A1.3"

\s

Matches any white-space character.

\w\s

"D " in "ID A1.3"

\S

Matches any non-white-space character.

\s\S

" _" in "int __ctr"

\d

Matches any decimal digit.

\d

"4" in "4 = IV"

\D

Matches any character other than a decimal digit.

\D

" ", "=", " ", "I", "V" in "4 = IV"

Back to top

Anchors, or atomic zero-width assertions, cause a match to succeed or fail depending on the current position in the string, but they do not cause the engine to advance through the string or consume characters. The metacharacters listed in the following table are anchors. For more information, see Anchors in Regular Expressions.

Assertion

Description

Pattern

Matches

^

The match must start at the beginning of the string or line.

^\d{3}

"901" in

"901-333-"

$

The match must occur at the end of the string or before \n at the end of the line or string.

-\d{3}$

"-333" in

"-901-333"

\A

The match must occur at the start of the string.

\A\d{3}

"901" in

"901-333-"

\Z

The match must occur at the end of the string or before \n at the end of the string.

-\d{3}\Z

"-333" in

"-901-333"

\z

The match must occur at the end of the string.

-\d{3}\z

"-333" in

"-901-333"

\G

The match must occur at the point where the previous match ended.

\G\(\d\)

"(1)", "(3)", "(5)" in "(1)(3)(5)[7](9)"

\b

The match must occur on a boundary between a \w (alphanumeric) and a \W (nonalphanumeric) character.

\b\w+\s\w+\b

"them theme", "them them" in "them theme them them"

\B

The match must not occur on a \b boundary.

\Bend\w*\b

"ends", "ender" in "end sends endure lender"

Back to top

Grouping constructs delineate subexpressions of a regular expression and typically capture substrings of an input string. Grouping constructs include the language elements listed in the following table. For more information, see Grouping Constructs in Regular Expressions.

Grouping construct

Description

Pattern

Matches

( subexpression )

Captures the matched subexpression and assigns it a one-based ordinal number.

(\w)\1

"ee" in "deep"

(?< name >subexpression)

Captures the matched subexpression into a named group.

(?<double>\w)\k<double>

"ee" in "deep"

(?< name1 - name2 >subexpression)

Defines a balancing group definition. For more information, see the "Balancing Group Definition" section in Grouping Constructs in Regular Expressions.

(((?'Open'\()[^\(\)]*)+((?'Close-Open'\))[^\(\)]*)+)*(?(Open)(?!))$

"((1-3)*(3-1))" in "3+2^((1-3)*(3-1))"

(?: subexpression)

Defines a noncapturing group.

Write(?:Line)?

"WriteLine" in "Console.WriteLine()"

(?imnsx-imnsx:subexpression)

Applies or disables the specified options within subexpression. For more information, seeRegular Expression Options.

A\d{2}(?i:\w+)\b

"A12xl", "A12XL" in "A12xl A12XL a12xl"

(?= subexpression)

Zero-width positive lookahead assertion.

\w+(?=\.)

"is", "ran", and "out" in "He is. The dog ran. The sun is out."

(?! subexpression)

Zero-width negative lookahead assertion.

\b(?!un)\w+\b

"sure", "used" in "unsure sure unity used"

(?<= subexpression)

Zero-width positive lookbehind assertion.

(?<=19)\d{2}\b

"99", "50", "05" in "1851 1999 1950 1905 2003"

(?<! subexpression)

Zero-width negative lookbehind assertion.

(?<!19)\d{2}\b

"51", "03" in "1851 1999 1950 1905 2003"

(?> subexpression)

Nonbacktracking (or "greedy") subexpression.

[13579](?>A+B+)

"1ABB", "3ABB", and "5AB" in "1ABB 3ABBC 5AB 5AC"

Back to top

A quantifier specifies how many instances of the previous element (which can be a character, a group, or a character class) must be present in the input string for a match to occur. Quantifiers include the language elements listed in the following table. For more information, see Quantifiers in Regular Expressions.

Quantifier

Description

Pattern

Matches

*

Matches the previous element zero or more times.

\d*\.\d

".0", "19.9", "219.9"

+

Matches the previous element one or more times.

"be+"

"bee" in "been", "be" in "bent"

?

Matches the previous element zero or one time.

"rai?n"

"ran", "rain"

{ n }

Matches the previous element exactly n times.

",\d{3}"

",043" in "1,043.6", ",876", ",543", and ",210" in "9,876,543,210"

{ n ,}

Matches the previous element at least n times.

"\d{2,}"

"166", "29", "1930"

{ n , m }

Matches the previous element at least n times, but no more than m times.

"\d{3,5}"

"166", "17668"

"19302" in "193024"

*?

Matches the previous element zero or more times, but as few times as possible.

\d*?\.\d

".0", "19.9", "219.9"

+?

Matches the previous element one or more times, but as few times as possible.

"be+?"

"be" in "been", "be" in "bent"

??

Matches the previous element zero or one time, but as few times as possible.

"rai??n"

"ran", "rain"

{ n }?

Matches the preceding element exactly n times.

",\d{3}?"

",043" in "1,043.6", ",876", ",543", and ",210" in "9,876,543,210"

{ n ,}?

Matches the previous element at least n times, but as few times as possible.

"\d{2,}?"

"166", "29", "1930"

{ n , m }?

Matches the previous element between n and m times, but as few times as possible.

"\d{3,5}?"

"166", "17668"

"193", "024" in "193024"

Back to top

A backreference allows a previously matched subexpression to be identified subsequently in the same regular expression. The following table lists the backreference constructs supported by regular expressions in the .NET Framework. For more information, see Backreference Constructs in Regular Expressions.

Backreference construct

Description

Pattern

Matches

\ number

Backreference. Matches the value of a numbered subexpression.

(\w)\1

"ee" in "seek"

\k< name >

Named backreference. Matches the value of a named expression.

(?<char>\w)\k<char>

"ee" in "seek"

Back to top

Alternation constructs modify a regular expression to enable either/or matching. These constructs include the language elements listed in the following table. For more information, see Alternation Constructs in Regular Expressions.

Alternation construct

Description

Pattern

Matches

|

Matches any one element separated by the vertical bar (|) character.

th(e|is|at)

"the", "this" in "this is the day. "

(?( expression )yes | no )

Matches yes if the regular expression pattern designated by expression matches; otherwise, matches the optional nopart. expression is interpreted as a zero-width assertion.

(?(A)A\d{2}\b|\b\d{3}\b)

"A10", "910" in "A10 C103 910"

(?( name ) yes |no )

Matches yes if name, a named or numbered capturing group, has a match; otherwise, matches the optional no.

(?<quoted>")?(?(quoted).+?"|\S+\s)

Dogs.jpg, "Yiska playing.jpg" in "Dogs.jpg "Yiska playing.jpg""

Back to top

Substitutions are regular expression language elements that are supported in replacement patterns. For more information, see Substitutions in Regular Expressions. The metacharacters listed in the following table are atomic zero-width assertions.

Character

Description

Pattern

Replacement pattern

Input string

Result string

$ number

Substitutes the substring matched by group number.

\b(\w+)(\s)(\w+)\b

$3$2$1

"one two"

"two one"

${ name }

Substitutes the substring matched by the named group name.

\b(?<word1>\w+)(\s)(?<word2>\w+)\b

${word2} ${word1}

"one two"

"two one"

$$

Substitutes a literal "$".

\b(\d+)\s?USD

$$$1

"103 USD"

"$103"

$&

Substitutes a copy of the whole match.

(\$*(\d*(\.+\d+)?){1})

**$&

"$1.30"

"**$1.30**"

$`

Substitutes all the text of the input string before the match.

B+

$`

"AABBCC"

"AAAACC"

$'

Substitutes all the text of the input string after the match.

B+

$'

"AABBCC"

"AACCCC"

$+

Substitutes the last group that was captured.

B+(C+)

$+

"AABBCCDD"

AACCDD

$_

Substitutes the entire input string.

B+

$_

"AABBCC"

"AAAABBCCCC"

Back to top

You can specify options that control how the regular expression engine interprets a regular expression pattern. Many of these options can be specified either inline (in the regular expression pattern) or as one or more RegexOptions constants. This quick reference lists only inline options. For more information about inline and RegexOptions options, see the article Regular Expression Options.

You can specify an inline option in two ways:

  • By using the miscellaneous construct (?imnsx-imnsx), where a minus sign (-) before an option or set of options turns those options off. For example, (?i-mn) turns case-insensitive matching (i) on, turns multiline mode (m) off, and turns unnamed group captures (n) off. The option applies to the regular expression pattern from the point at which the option is defined, and is effective either to the end of the pattern or to the point where another construct reverses the option.

  • By using the grouping construct (?imnsx-imnsx:subexpression), which defines options for the specified group only.

The .NET Framework regular expression engine supports the following inline options.

Option

Description

Pattern

Matches

i

Use case-insensitive matching.

\b(?i)a(?-i)a\w+\b

"aardvark", "aaaAuto" in "aardvark AAAuto aaaAuto Adam breakfast"

m

Use multiline mode. ^ and $ match the beginning and end of a line, instead of the beginning and end of a string.

For an example, see the "Multiline Mode" section in Regular Expression Options.

n

Do not capture unnamed groups.

For an example, see the "Explicit Captures Only" section inRegular Expression Options.

s

Use single-line mode.

For an example, see the "Single-line Mode" section in Regular Expression Options.

x

Ignore unescaped white space in the regular expression pattern.

\b(?x) \d+ \s \w+

"1 aardvark", "2 cats" in "1 aardvark 2 cats IV centurions"

Back to top

Miscellaneous constructs either modify a regular expression pattern or provide information about it. The following table lists the miscellaneous constructs supported by the .NET Framework. For more information, see Miscellaneous Constructs in Regular Expressions.

Construct

Definition

Example

(?imnsx-imnsx)

Sets or disables options such as case insensitivity in the middle of a pattern. For more information, see Regular Expression Options.

\bA(?i)b\w+\b matches "ABA", "Able" in "ABA Able Act"

(?# comment)

Inline comment. The comment ends at the first closing parenthesis.

\bA(?#Matches words starting with A)\w+\b

# [to end of line]

X-mode comment. The comment starts at an unescaped # and continues to the end of the line.

(?x)\bA\w+\b#Matches words starting with A

Back to top


반응형
반응형



소개글 : http://web-dev.tistory.com/562


위의 글은 아크로 에디터를 다운로드 받는 등 간단한 소개 내역이다.


사실 


울트라 에디터를 사용했던 주된 이유는 


대용량 한글 텍스트 파일(1GB 이상)을 부담없이 열어주며,


정규식 표현으로 특정 단어 + 다음줄 변환이 가능했기 때문이다.


그동안 아크로 에디터에서는 안되는 줄 알았는데,...


제 무지였음을 깨닿고 내용을 남깁니다.



-> 대용량 텍스트 연계 파일의 경우


DxxxxDxxxDxxx 등과 같이 특정 단어로 시작하는 경우가 많다.


그럴 경우


1. 아크로에디트 -> 찾기 -> 바꾸기 실행

    



2. 아래는 바꾼 후의 사진

    - 멋지지 않은가?

      실제 사례로... xml 태그 같은 경우

      찾는 문자열 : ><

      바꿀 문자열 : >\n< 

     정규 표현식 사용 체크, 범위 전체 체크 하면

     깔끔한 형태로 보여진다.


3. 기타 팁

    편집 -> 모두 선택 (전체가 블록 지정된 상태) -> 도구 -> 빈 줄 자동 삭제

    즉 필요없이 엔터가 많은 파일에서는 위의 설정을 선택하면 모든 빈줄이 사라진다 !



   


반응형
반응형
반응형
반응형


포터블이라...

32 or 64 비트 맞춰서 쓰면 됨....

2003/xp/vista/Windows 7 지원

사용법 ~

1. x86이든 폴더에 들어가서  Unlocker.exe 실행

2. 삭제 안되는 파일이나 폴더를 지정함

3. 왼쪽 아래의 드래그 목록에서 delete 를 선택하고 unlock all 등을 선택하면
   권한 풀고 삭제가 이루어짐
   만약 안된다면 리부팅 한번 하면 됨...

반응형

'UTILITY' 카테고리의 다른 글

별표시 되는 암호 필드 값 조회 프로그램  (0) 2011.02.17
TCO Stream 제거  (0) 2011.02.16
VI 완전 정복하기  (1) 2011.01.06
vmplayer 3.1.1 개인용  (1) 2010.12.10
VMWARE 속도 튜닝 하기  (1) 2010.12.07
반응형

출처(Reference) : http://www.javafaq.nu/java-example-code-141.html


// -----------------------------------------------------------------------------
// CLOBFileExample.java
// -----------------------------------------------------------------------------

/*
 * =============================================================================
 * Copyright (c) 1998-2005 Jeffrey M. Hunter. All rights reserved.
 *
 * All source code and material located at the Internet address of
 * http://www.idevelopment.info is the copyright of Jeffrey M. Hunter, 2005 and
 * is protected under copyright laws of the United States. This source code may
 * not be hosted on any other site without my express, prior, written
 * permission. Application to host any of the material elsewhere can be made by
 * contacting me at jhunter@idevelopment.info.
 *
 * I have made every effort and taken great care in making sure that the source
 * code and other content included on my web site is technically accurate, but I
 * disclaim any and all responsibility for any loss, damage or destruction of
 * data or any other property which may arise from relying on it. I will in no
 * case be liable for any monetary damages arising from such loss, damage or
 * destruction.
 *
 * As with any code, ensure to test this code in a development environment
 * before attempting to run it in production.
 * =============================================================================
 */
 
import java.sql.*;
import java.io.*;
import java.util.*;

// Needed since we will be using Oracle's CLOB, part of Oracle's JDBC extended
// classes. Keep in mind that we could have included Java's JDBC interfaces
// java.sql.Clob which Oracle does implement. The oracle.sql.CLOB class
// provided by Oracle does offer better performance and functionality.
import oracle.sql.*;

// Needed for Oracle JDBC Extended Classes
import oracle.jdbc.*;


/**
 * -----------------------------------------------------------------------------
 * Used to test the functionality of how to load and unload text data from an
 * Oracle CLOB.
 *
 * This example uses an Oracle table with the following definition:
 *
 *      CREATE TABLE test_clob (
 *            id               NUMBER(15)
 *          , do*****ent_name    VARCHAR2(1000)
 *          , xml_do*****ent     CLOB
 *          , timestamp        DATE
 *      );
 * -----------------------------------------------------------------------------
 * @version 1.0
 * @author  Jeffrey M. Hunter  (jhunter@idevelopment.info)
 * @author  http://www.idevelopment.info
 * -----------------------------------------------------------------------------
 */
 
public class CLOBFileExample  {

    private String          inputTextFileName   = null;
    private File            inputTextFile       = null;

    private String          outputTextFileName1  = null;
    private File            outputTextFile1      = null;

    private String          outputTextFileName2  = null;
    private File            outputTextFile2      = null;
   
    private String          dbUser              = "SCOTT";
    private String          dbPassword          = "TIGER";
    private Connection      conn                = null;
   

    /**
     * Default constructor used to create this object. Responsible for setting
     * this object's creation date, as well as incrementing the number instances
     * of this object.
     * @param args Array of string arguments passed in from the command-line.
     * @throws java.io.IOException
     */
    public CLOBFileExample(String[] args) throws IOException {
       
        inputTextFileName  = args[0];
        inputTextFile = new File(inputTextFileName);
       
        if (!inputTextFile.exists()) {
            throw new IOException("File not found. " + inputTextFileName);
        }

        outputTextFileName1 = inputTextFileName + ".getChars.out";
        outputTextFileName2 = inputTextFileName + ".Streams.out";
       
    }


    /**
     * Obtain a connection to the Oracle database.
     * @throws java.sql.SQLException
     */
    public void openOracleConnection()
            throws    SQLException
                    , IllegalAccessException
                    , InstantiationException
                    , ClassNotFoundException {

        String driver_class  = "oracle.jdbc.driver.OracleDriver";
        String connectionURL = null;

        try {
            Class.forName (driver_class).newInstance();
            connectionURL = "jdbc:oracle:thin:@melody:1521:JEFFDB";
            conn = DriverManager.getConnection(connectionURL, dbUser, dbPassword);
            conn.setAutoCommit(false);
            System.out.println("Connected.\n");
        } catch (IllegalAccessException e) {
            System.out.println("Illegal Access Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        } catch (InstantiationException e) {
            System.out.println("Instantiation Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        } catch (ClassNotFoundException e) {
            System.out.println("Class Not Found Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        }
           
    }
   
   
    /**
     * Close Oracle database connection.
     * @throws java.sql.SQLException
     */
    public void closeOracleConnection() throws SQLException {
       
        try {
            conn.close();
            System.out.println("Disconnected.\n");
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Closing Connection).");
            e.printStackTrace();
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException e2) {
                    System.out.println("Caught SQL (Rollback Failed) Exception.");
                    e2.printStackTrace();
                }
            }
            throw e;
        }

    }
   
   
    /**
     * Method used to print program usage to the console.
     */
    static public void usage() {
        System.out.println("\nUsage: java CLOBFileExample \"Text File Name\"\n");
    }


    /**
     * Validate command-line arguments to this program.
     * @param args Array of string arguments passed in from the command-line.
     * @return Boolean - value of true if correct arguments, false otherwise.
     */
    static public boolean checkArguments(String[] args) {
       
        if (args.length == 1) {
            return true;
        } else {
            return false;
        }

    }


    /**
     * Override the Object toString method. Used to print a version of this
     * object to the console.
     * @return String - String to be returned by this object.
     */
    public String toString() {
   
        String retValue;

        retValue  = "Input File         : " + inputTextFileName    + "\n" +
                    "Output File (1)    : " + outputTextFileName1  + "\n" +
                    "Output File (2)    : " + outputTextFileName2  + "\n" +
                    "Database User      : " + dbUser;
        return retValue;
   
    }


    /**
     * Method used to write text data contained in a file to an Oracle CLOB
     * column. The method used to write the data to the CLOB uses the putChars()
     * method. This is one of two types of methods used to write text data to
     * a CLOB column. The other method uses Streams.
     *
     * @throws java.io.IOException
     * @throws java.sql.SQLException
     */
    public void writeCLOBPut()
            throws IOException, SQLException {
       
        FileInputStream     inputFileInputStream    = null;
        InputStreamReader   inputInputStreamReader  = null;
        BufferedReader      inputBufferedReader     = null;
        String              sqlText                 = null;
        Statement           stmt                    = null;
        ResultSet           rset                    = null;
        CLOB                xmlDo*****ent             = null;
        int                 chunkSize;
        char[]              textBuffer;
        long                position;
        int                 charsRead               = 0;
        int                 charsWritten            = 0;
        int                 totCharsRead            = 0;
        int                 totCharsWritten         = 0;
       
        try {

            stmt = conn.createStatement();
           
            inputTextFile = new File(inputTextFileName);
            inputFileInputStream = new FileInputStream(inputTextFile);
            inputInputStreamReader = new InputStreamReader(inputFileInputStream);
            inputBufferedReader = new BufferedReader(inputInputStreamReader);
       
            sqlText =
                "INSERT INTO test_clob (id, do*****ent_name, xml_do*****ent, timestamp) " +
                "   VALUES(1, '" + inputTextFile.getName() + "', EMPTY_CLOB(), SYSDATE)";
            stmt.executeUpdate(sqlText);
           
            sqlText =
                "SELECT xml_do*****ent " +
                "FROM   test_clob " +
                "WHERE  id = 1 " +
                "FOR UPDATE";
            rset = stmt.executeQuery(sqlText);
            rset.next();
            xmlDo*****ent = ((OracleResultSet) rset).getCLOB("xml_do*****ent");
           
            chunkSize = xmlDo*****ent.getChunkSize();
            textBuffer = new char[chunkSize];
           
            position = 1;
            while ((charsRead = inputBufferedReader.read(textBuffer)) != -1) {
                charsWritten = xmlDo*****ent.putChars(position, textBuffer, charsRead);
                position        += charsRead;
                totCharsRead    += charsRead;
                totCharsWritten += charsWritten;
            }
           
            inputBufferedReader.close();
            inputInputStreamReader.close();
            inputFileInputStream.close();

            conn.commit();
            rset.close();
            stmt.close();
           
            System.out.println(
                "==========================================================\n" +
                "  PUT METHOD\n" +
                "==========================================================\n" +
                "Wrote file " + inputTextFile.getName() + " to CLOB column.\n" +
                totCharsRead + " characters read.\n" +
                totCharsWritten + " characters written.\n"
            );

        } catch (IOException e) {
            System.out.println("Caught I/O Exception: (Write CLOB value - Put Method).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Write CLOB value - Put Method).");
            System.out.println("SQL:\n" + sqlText);
            e.printStackTrace();
            throw e;
        }

    }

   
    /**
     * Method used to write the contents (data) from an Oracle CLOB column to
     * an O/S file. This method uses one of two ways to get data from the CLOB
     * column - namely the getChars() method. The other way to read data from an
     * Oracle CLOB column is to use Streams.
     *
     * @throws java.io.IOException
     * @throws java.sql.SQLException
     */
    public void readCLOBToFileGet()
            throws IOException, SQLException {

        FileOutputStream    outputFileOutputStream      = null;
        OutputStreamWriter  outputOutputStreamWriter    = null;
        BufferedWriter      outputBufferedWriter        = null;
        String              sqlText                     = null;
        Statement           stmt                        = null;
        ResultSet           rset                        = null;
        CLOB                xmlDo*****ent                 = null;
        long                clobLength;
        long                position;
        int                 chunkSize;
        char[]              textBuffer;
        int                 charsRead                   = 0;
        int                 charsWritten                = 0;
        int                 totCharsRead                = 0;
        int                 totCharsWritten             = 0;

        try {

            stmt = conn.createStatement();

            outputTextFile1 = new File(outputTextFileName1);
            outputFileOutputStream = new FileOutputStream(outputTextFile1);
            outputOutputStreamWriter = new OutputStreamWriter(outputFileOutputStream);
            outputBufferedWriter = new BufferedWriter(outputOutputStreamWriter);

            sqlText =
                "SELECT xml_do*****ent " +
                "FROM   test_clob " +
                "WHERE  id = 1 " +
                "FOR UPDATE";
            rset = stmt.executeQuery(sqlText);
            rset.next();
            xmlDo*****ent = ((OracleResultSet) rset).getCLOB("xml_do*****ent");
           
            clobLength = xmlDo*****ent.length();
            chunkSize = xmlDo*****ent.getChunkSize();
            textBuffer = new char[chunkSize];
           
            for (position = 1; position <= clobLength; position += chunkSize) {
               
                // Loop through while reading a chunk of data from the CLOB
                // column using the getChars() method. This data will be stored
                // in a temporary buffer that will be written to disk.
                charsRead = xmlDo*****ent.getChars(position, chunkSize, textBuffer);

                // Now write the buffer to disk.
                outputBufferedWriter.write(textBuffer, 0, charsRead);
               
                totCharsRead += charsRead;
                totCharsWritten += charsRead;

            }

            outputBufferedWriter.close();
            outputOutputStreamWriter.close();
            outputFileOutputStream.close();
           
            conn.commit();
            rset.close();
            stmt.close();
           
            System.out.println(
                "==========================================================\n" +
                "  GET METHOD\n" +
                "==========================================================\n" +
                "Wrote CLOB column data to file " + outputTextFile1.getName() + ".\n" +
                totCharsRead + " characters read.\n" +
                totCharsWritten + " characters written.\n"
            );

        } catch (IOException e) {
            System.out.println("Caught I/O Exception: (Write CLOB value to file - Get Method).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Write CLOB value to file - Get Method).");
            System.out.println("SQL:\n" + sqlText);
            e.printStackTrace();
            throw e;
        }

    }
   
   
    /**
     * Method used to write text data contained in a file to an Oracle CLOB
     * column. The method used to write the data to the CLOB uses Streams.
     * This is one of two types of methods used to write text data to
     * a CLOB column. The other method uses the putChars() method.
     *
     * @throws java.io.IOException
     * @throws java.sql.SQLException
     */
    public void writeCLOBStream()
            throws IOException, SQLException {

        FileInputStream     inputFileInputStream    = null;
        OutputStream        clobOutputStream        = null;
        String              sqlText                 = null;
        Statement           stmt                    = null;
        ResultSet           rset                    = null;
        CLOB                xmlDo*****ent             = null;
        int                 bufferSize;
        byte[]              byteBuffer;
        int                 bytesRead               = 0;
        int                 bytesWritten            = 0;
        int                 totBytesRead            = 0;
        int                 totBytesWritten         = 0;

        try {

            stmt = conn.createStatement();

            inputTextFile = new File(inputTextFileName);
            inputFileInputStream = new FileInputStream(inputTextFile);
           
            sqlText =
                "INSERT INTO test_clob (id, do*****ent_name, xml_do*****ent, timestamp) " +
                "   VALUES(2, '" + inputTextFile.getName() + "', EMPTY_CLOB(), SYSDATE)";
            stmt.executeUpdate(sqlText);
           
            sqlText =
                "SELECT xml_do*****ent " +
                "FROM   test_clob " +
                "WHERE  id = 2 " +
                "FOR UPDATE";
            rset = stmt.executeQuery(sqlText);
            rset.next();
            xmlDo*****ent = ((OracleResultSet) rset).getCLOB("xml_do*****ent");
           
            bufferSize = xmlDo*****ent.getBufferSize();
           
            // Notice that we are using an array of bytes as opposed to an array
            // of characters. This is required since we will be streaming the
            // content (to either a CLOB or BLOB) as a stream of bytes using
            // using an OutputStream Object. This requires that a byte array to
            // be used to temporarily store the contents that will be sent to
            // the LOB. Note that they use of the byte array can be used even
            // when reading contents from an ASCII text file that will be sent
            // to a CLOB.
            byteBuffer = new byte[bufferSize];
           
            clobOutputStream = xmlDo*****ent.getAsciiOutputStream();
           
            while ((bytesRead = inputFileInputStream.read(byteBuffer)) != -1) {
           
                // After reading a buffer from the text file, write the contents
                // of the buffer to the output stream using the write()
                // method.
                clobOutputStream.write(byteBuffer, 0, bytesRead);
               
                totBytesRead += bytesRead;
                totBytesWritten += bytesRead;

            }

            // Keep in mind that we still have the stream open. Once the stream
            // gets open, you cannot perform any other database operations
            // until that stream has been closed. This even includes a COMMIT
            // statement. It is possible to loose data from the stream if this
            // rule is not followed. If you were to attempt to put the COMMIT in
            // place before closing the stream, Oracle will raise an
            // "ORA-22990: LOB locators cannot span transactions" error.

            inputFileInputStream.close();
            clobOutputStream.close();
           
            conn.commit();
            rset.close();
            stmt.close();

            System.out.println(
                "==========================================================\n" +
                "  OUTPUT STREAMS METHOD\n" +
                "==========================================================\n" +
                "Wrote file " + inputTextFile.getName() + " to CLOB column.\n" +
                totBytesRead + " bytes read.\n" +
                totBytesWritten + " bytes written.\n"
            );

        } catch (IOException e) {
            System.out.println("Caught I/O Exception: (Write CLOB value - Stream Method).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Write CLOB value - Stream Method).");
            System.out.println("SQL:\n" + sqlText);
            e.printStackTrace();
            throw e;
        }

    }
   
   
    /**
     * Method used to write the contents (data) from an Oracle CLOB column to
     * an O/S file. This method uses one of two ways to get data from the CLOB
     * column - namely using Streams. The other way to read data from an
     * Oracle CLOB column is to use getChars() method.
     *
     * @throws java.io.IOException
     * @throws java.sql.SQLException
     */
    public void readCLOBToFileStream()
            throws IOException, SQLException {

        FileOutputStream    outputFileOutputStream      = null;
        InputStream         clobInputStream             = null;
        String              sqlText                     = null;
        Statement           stmt                        = null;
        ResultSet           rset                        = null;
        CLOB                xmlDo*****ent                 = null;
        int                 chunkSize;
        byte[]              textBuffer;
        int                 bytesRead                   = 0;
        int                 bytesWritten                = 0;
        int                 totBytesRead                = 0;
        int                 totBytesWritten             = 0;

        try {

            stmt = conn.createStatement();

            outputTextFile2 = new File(outputTextFileName2);
            outputFileOutputStream = new FileOutputStream(outputTextFile2);

            sqlText =
                "SELECT xml_do*****ent " +
                "FROM   test_clob " +
                "WHERE  id = 2 " +
                "FOR UPDATE";
            rset = stmt.executeQuery(sqlText);
            rset.next();
            xmlDo*****ent = ((OracleResultSet) rset).getCLOB("xml_do*****ent");

            // Will use a Java InputStream object to read data from a CLOB (can
            // also be used for a BLOB) object. In this example, we will use an
            // InputStream to read ASCII characters from a CLOB.
            clobInputStream = xmlDo*****ent.getAsciiStream();
           
            chunkSize = xmlDo*****ent.getChunkSize();
            textBuffer = new byte[chunkSize];
           
            while ((bytesRead = clobInputStream.read(textBuffer)) != -1) {
               
                // Loop through while reading a chunk of data from the CLOB
                // column using an InputStream. This data will be stored
                // in a temporary buffer that will be written to disk.
                outputFileOutputStream.write(textBuffer, 0, bytesRead);
               
                totBytesRead += bytesRead;
                totBytesWritten += bytesRead;

            }

            outputFileOutputStream.close();
            clobInputStream.close();
           
            conn.commit();
            rset.close();
            stmt.close();
           
            System.out.println(
                "==========================================================\n" +
                "  INPUT STREAMS METHOD\n" +
                "==========================================================\n" +
                "Wrote CLOB column data to file " + outputTextFile2.getName() + ".\n" +
                totBytesRead + " characters read.\n" +
                totBytesWritten + " characters written.\n"
            );

        } catch (IOException e) {
            System.out.println("Caught I/O Exception: (Write CLOB value to file - Streams Method).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Write CLOB value to file - Streams Method).");
            System.out.println("SQL:\n" + sqlText);
            e.printStackTrace();
            throw e;
        }
       
    }
   
   
    /**
     * Sole entry point to the class and application.
     * @param args Array of string arguments passed in from the command-line.
     */
    public static void main(String[] args) {
   
        CLOBFileExample cLOBFileExample = null;
       
        if (checkArguments(args)) {

            try {
               
                cLOBFileExample = new CLOBFileExample(args);
               
                System.out.println("\n" + cLOBFileExample + "\n");
               
                cLOBFileExample.openOracleConnection();
               
                cLOBFileExample.writeCLOBPut();
                cLOBFileExample.readCLOBToFileGet();
               
                cLOBFileExample.writeCLOBStream();
                cLOBFileExample.readCLOBToFileStream();
               
                cLOBFileExample.closeOracleConnection();

            } catch (IllegalAccessException e) {
                System.out.println("Caught Illegal Accecss Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            } catch (InstantiationException e) {
                System.out.println("Instantiation Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            } catch (ClassNotFoundException e) {
                System.out.println("Class Not Found Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            } catch (SQLException e) {
                System.out.println("Caught SQL Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            } catch (IOException e) {
                System.out.println("Caught I/O Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            }

        } else {
            System.out.println("\nERROR: Invalid arguments.");
            usage();
            System.exit(1);
        }
       
        System.exit(0);
    }

반응형
반응형

.bff 파일은 AIX 시스템에서는

다음과 같이 설치가능하다.

1. java1.4.2.bff 파일을 FTP를 사용하여 AIX 시스템에 upload(/tmp/java14/)

2. root로 접근하여 smitty install or smitty installp 하여 해당 디렉토리(/tmp/java14/)를 설치하면
   자동으로 설치됨.
반응형

'OS > AIX' 카테고리의 다른 글

날짜 관련 얻기  (0) 2011.03.02
AIX 5.3 OPENSSH INSTALL  (0) 2011.02.16
IBM AIX 용 JAVA 다운로드 주소  (0) 2010.12.07
AIX 5.3에서 Tomcat 설치 및 기본 홈 디렉토리 변경  (1) 2010.12.07
AIX 시스템 점검 쉘  (0) 2010.06.04
반응형

Multifile storage with Zip

The library that supports the Zip format is much more extensive. With it you can easily store multiple files, and there’s even a separate class to make the process of reading a Zip file easy. The library uses the standard Zip format so that it works seamlessly with all the tools currently downloadable on the Internet. The following example has the same form as the previous example, but it handles as many command-line arguments as you want. In addition, it shows the use of the Checksum classes to calculate and verify the checksum for the file. There are two Checksum types: Adler32 (which is faster) and CRC32 (which is slower but slightly more accurate).

//: c12:ZipCompress.java
// Uses Zip compression to compress any
// number of files given on the command line.
// {Args: ZipCompress.java}
// {Clean: test.zip}
import com.bruceeckel.simpletest.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;

public class ZipCompress {
  private static Test monitor = new Test();
  // Throw exceptions to console:
  public static void main(String[] args)
  throws IOException {
    FileOutputStream f = new FileOutputStream("test.zip");
    CheckedOutputStream csum =
      new CheckedOutputStream(f, new Adler32());
     ZipOutputStream zos = new ZipOutputStream(csum);
     BufferedOutputStream out =
      new BufferedOutputStream(zos);
    zos.setComment("A test of Java Zipping");
    // No corresponding getComment(), though.
    for(int i = 0; i < args.length; i++) {
      System.out.println("Writing file " + args[i]);
      BufferedReader in =
        new BufferedReader(new FileReader(args[i]));
      zos.putNextEntry(new ZipEntry(args[i]));
      int c;
      while((c = in.read()) != -1)
        out.write(c);
      in.close();
    }
    out.close();
    // Checksum valid only after the file has been closed!
    System.out.println("Checksum: " +
      csum.getChecksum().getValue());
    // Now extract the files:
    System.out.println("Reading file");
    FileInputStream fi = new FileInputStream("test.zip");
    CheckedInputStream csumi =
      new CheckedInputStream(fi, new Adler32());
    ZipInputStream in2 = new ZipInputStream(csumi);
    BufferedInputStream bis = new BufferedInputStream(in2);
    ZipEntry ze;
    while((ze = in2.getNextEntry()) != null) {
      System.out.println("Reading file " + ze);
      int x;
      while((x = bis.read()) != -1)
        System.out.write(x);
    }
    if(args.length == 1)
      monitor.expect(new String[] {
        "Writing file " + args[0],
        "%% Checksum: \\d+",
        "Reading file",
        "Reading file " + args[0]}, args[0]);
    System.out.println("Checksum: " +
      csumi.getChecksum().getValue());
    bis.close();
    // Alternative way to open and read zip files:
    ZipFile zf = new ZipFile("test.zip");
    Enumeration e = zf.entries();
    while(e.hasMoreElements()) {
      ZipEntry ze2 = (ZipEntry)e.nextElement();
      System.out.println("File: " + ze2);
      // ... and extract the data as before
    }
    if(args.length == 1)
      monitor.expect(new String[] {
        "%% Checksum: \\d+",
        "File: " + args[0]
      });
  }
} ///:~


For each file to add to the archive, you must call putNextEntry( ) and pass it a ZipEntry object. The ZipEntry object contains an extensive interface that allows you to get and set all the data available on that particular entry in your Zip file: name, compressed and uncompressed sizes, date, CRC checksum, extra field data, comment, compression method, and whether it’s a directory entry. However, even though the Zip format has a way to set a password, this is not supported in Java’s Zip library. And although CheckedInputStream and CheckedOutputStream support both Adler32 and CRC32 checksums, the ZipEntry class supports only an interface for CRC. This is a restriction of the underlying Zip format, but it might limit you from using the faster Adler32.

To extract files, ZipInputStream has a getNextEntry( ) method that returns the next ZipEntry if there is one. As a more succinct alternative, you can read the file using a ZipFile object, which has a method entries( ) to return an Enumeration to the ZipEntries.

In order to read the checksum, you must somehow have access to the associated Checksum object. Here, a reference to the CheckedOutputStream and CheckedInputStream objects is retained, but you could also just hold onto a reference to the Checksum object.

A baffling method in Zip streams is setComment( ). As shown in ZipCompress.java, you can set a comment when you’re writing a file, but there’s no way to recover the comment in the ZipInputStream. Comments appear to be supported fully on an entry-by-entry basis only via ZipEntry.

Of course, you are not limited to files when using the GZIP or Zip libraries—you can compress anything, including data to be sent through a network connection.

출처 : http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ314_033.htm

반응형

'Language > JAVA' 카테고리의 다른 글

Heap Dump 분석을 통한 Perm Area Memory Leak 원인 진단  (0) 2010.12.14
Java ARchives (JAR)  (0) 2010.11.17
자바 간단한 GZIP 압축 예제  (0) 2010.11.17
자바 파일 압축  (0) 2010.11.17
JAVA File Locking(자바 파일 잠금)  (0) 2010.11.17
반응형

File locking

File locking, introduced in JDK 1.4, allows you to synchronize access to a file as a shared resource. However, the two threads that contend for the same file may be in different JVMs, or one may be a Java thread and the other some native thread in the operating system. The file locks are visible to other operating system processes because Java file locking maps directly to the native operating system locking facility.

Here is a simple example of file locking.

//: c12:FileLocking.java
// {Clean: file.txt}
import java.io.FileOutputStream;
import java.nio.channels.*;

public class FileLocking {
  public static void main(String[] args) throws Exception {
    FileOutputStream fos= new FileOutputStream("file.txt");
    FileLock fl = fos.getChannel().tryLock();
    if(fl != null) {
      System.out.println("Locked File");
      Thread.sleep(100);
      fl.release();
      System.out.println("Released Lock");
    }
    fos.close();
  }
} ///:~


You get a FileLock on the entire file by calling either tryLock( ) or lock( ) on a FileChannel. (SocketChannel, DatagramChannel, and ServerSocketChannel do not need locking since they are inherently single-process entities; you don’t generally share a network socket between two processes.) tryLock( ) is non-blocking. It tries to grab the lock, but if it cannot (when some other process already holds the same lock and it is not shared), it simply returns from the method call. lock( ) blocks until the lock is acquired, or the thread that invoked lock( ) is interrupted, or the channel on which the lock( ) method is called is closed. A lock is released using FileLock.release( ).

It is also possible to lock a part of the file by using

tryLock(long position, long size, boolean shared)


or

lock(long position, long size, boolean shared)


which locks the region (size - position). The third argument specifies whether this lock is shared.

Although the zero-argument locking methods adapt to changes in the size of a file, locks with a fixed size do not change if the file size changes. If a lock is acquired for a region from position to position+size and the file increases beyond position+size, then the section beyond position+size is not locked. The zero-argument locking methods lock the entire file, even if it grows.

Support for exclusive or shared locks must be provided by the underlying operating system. If the operating system does not support shared locks and a request is made for one, an exclusive lock is used instead. The type of lock (shared or exclusive) can be queried using FileLock.isShared( ).

Locking portions of a mapped file

As mentioned earlier, file mapping is typically used for very large files. One thing that you may need to do with such a large file is to lock portions of it so that other processes may modify unlocked parts of the file. This is something that happens, for example, with a database, so that it can be available to many users at once.

Here’s an example that has two threads, each of which locks a distinct portion of a file:

//: c12:LockingMappedFiles.java
// Locking portions of a mapped file.
// {RunByHand}
// {Clean: test.dat}
import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class LockingMappedFiles {
  static final int LENGTH = 0x8FFFFFF; // 128 Mb
  static FileChannel fc;
  public static void main(String[] args) throws Exception {
    fc = 
      new RandomAccessFile("test.dat", "rw").getChannel();
    MappedByteBuffer out = 
      fc.map(FileChannel.MapMode.READ_WRITE, 0, LENGTH);
    for(int i = 0; i < LENGTH; i++)
      out.put((byte)'x');
    new LockAndModify(out, 0, 0 + LENGTH/3);
    new LockAndModify(out, LENGTH/2, LENGTH/2 + LENGTH/4);
  }
  private static class LockAndModify extends Thread {
    private ByteBuffer buff;
    private int start, end;
    LockAndModify(ByteBuffer mbb, int start, int end) {
      this.start = start;
      this.end = end;
      mbb.limit(end);
      mbb.position(start);
      buff = mbb.slice();
      start();
    }    
    public void run() {
      try {
        // Exclusive lock with no overlap:
        FileLock fl = fc.lock(start, end, false);
        System.out.println("Locked: "+ start +" to "+ end);
        // Perform modification:
        while(buff.position() < buff.limit() - 1)
          buff.put((byte)(buff.get() + 1));
        fl.release();
        System.out.println("Released: "+start+" to "+ end);
      } catch(IOException e) {
        throw new RuntimeException(e);
      }
    }
  }
} ///:~


The LockAndModify thread class sets up the buffer region and creates a slice( ) to be modified, and in run( ), the lock is acquired on the file channel (you can’t acquire a lock on the buffer—only the channel). The call to lock( ) is very similar to acquiring a threading lock on an object—you now have a “critical section” with exclusive access to that portion of the file.

The locks are automatically released when the JVM exits, or the channel on which it was acquired is closed, but you can also explicitly call release( ) on the FileLock object, as shown here.

출처 : http://www.linuxtopia.org/

반응형

+ Recent posts