검색결과 리스트
java에 해당되는 글 5건
- 2009.08.20 java5.0 ] 소수점 원하는 자릿수로 표현하기
- 2008.12.08 자바에서 외부파일 실행
- 2008.12.05 스윙] 웹상의 이미지 경로 로부터 파일저장
- 2008.12.01 JAVA 스윙 야구게임 프로그래밍
- 2008.07.29 Java] java.lang.reflect.* 활용
글
java5.0 ] 소수점 원하는 자릿수로 표현하기
int totResCnt = 44
int totCount = 8
String resPercent = "";
String pattern = "0.##";
DecimalFormat df = new DecimalFormat(pattern);
resPercent = df.format(((float)totResCnt/(float)totCount)*100);
설정
트랙백
댓글
글
자바에서 외부파일 실행
java.lang
클래스 Runtime
java.lang.Objectjava.lang.Runtime
자바에서 외부파일을 실행시키기 위해 사용되는 Runtime클래스
오버로딩 되어잇는 exec()메소드
Process |
exec (String command) 지정된 캐릭터 라인 커멘드를, 독립한 프로세스로 실행합니다. |
Process |
exec (String [] cmdarray) 지정된 커멘드와 인수를, 독립한 프로세스로 실행합니다. |
Process |
exec (String [] cmdarray, String [] envp) 지정된 커멘드와 인수를, 지정된 환경을 가지는 독립한 프로세스로 실행합니다. |
Process |
exec (String [] cmdarray, String [] envp, File dir) 지정된 커멘드와 인수를, 지정된 환경과 작업 디렉토리를 가지는 독립한 프로세스로 실행합니다. |
Process |
exec (String command, String [] envp) 지정된 캐릭터 라인 커멘드를, 지정된 환경을 가지는 독립한 프로세스로 실행합니다. |
Process |
exec (String command, String [] envp, File dir) 지정된 캐릭터 라인 커멘드를, 지정된 환경과 작업 디렉토리를 가지는 독립한 프로세스로 실행합니다. |
void |
exit (int status) 현재 실행하고 있는 Java 가상 머신을, 종료 순서를 개시해 종료합니다. |
자바에서 특정 외부파일을 실행시키기 위한 예제입니다.
방법1.
import java.io.InputStreamReader;
public class ProcessTest {
public static void main(String args[]) throws Exception{
Process p=Runtime.getRuntime().exec("C:/1.exe");
BufferedReader bf=new BufferedReader(new InputStreamReader(p.getErrorStream()));
String str="";
while((str=bf.readLine())!=null){
System.out.println(str);
}
BufferedReader bf1=new BufferedReader(new InputStreamReader(p.getInputStream()));
String str1="";
while((str1=bf1.readLine())!=null){
System.out.println(str1);
}
}
}
위의 내용을 클래스화 시켜서 별도의 클래스로 작성!
public class Executor
{
public static void execute(String command)
{
try
{
String cmd[] = new String[3];
cmd[0] = "cmd.exe";
cmd[1] = "/C";
cmd[2] = command;
Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]);
Process proc = rt.exec(cmd);
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
errorGobbler.start();
outputGobbler.start();
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
}
catch(Throwable t)
{
t.printStackTrace();
}
}
}
설정
트랙백
댓글
글
스윙] 웹상의 이미지 경로 로부터 파일저장
/*
웹상의 image url경로를 적어주게 되면 그 경로를 바탕으로 이미지를 로컬에 저장시켜주는 기능입니다.
아래 saveMethod는 다른이름으로 저장 버튼을 눌렀을시 이벤트가 발생하는 메서드입니다.
sava부분 로직만 참고!!
*/
private void savaMethod(java.awt.event.ActionEvent evt) {
/*===============================================================
* url_tf에 입력된 문자열을 가져온다. 그리고 그것이 비었는지 비교한후
* 저장할수 있는 JFileChooser를 생성한다.
* ==============================================================
*/
String url_path = url_tf.getText().trim();
if(url_path.length()>0){
JFileChooser fc = new JFileChooser("c:"+System.getProperty("file.separator"));
/*
* 저장시 JFilechooser창에 파일명이 설정되도록 하는 부분
*/
String f_name = url_path.substring(url_path.lastIndexOf("/")+1);
File set_name = new File("C:"+System.getProperty("file.separator")+f_name);
fc.setSelectedFile(set_name); // JFileChooser 창열릴시 파일명을 표시
int cmd = fc.showSaveDialog(this);
if(cmd==JFileChooser.APPROVE_OPTION){
/*
* 실제 저장할 파일은 웹상에 존재한다. 그것과
* 연결하여 현재 소스로 자원을 읽어올 통로(배관)이 필요한다.
* 웹사이트 문서와 연결이기 때문에 url객체 생성
*/
InputStream input = null;
FileOutputStream fos = null;
try {
input = new URL(url_path).openStream();
File f = fc.getSelectedFile();
/* =============================================================
* 이제 위에서 선택된 파일과 통로을 연결하여 자원들을 저장할수 있도록
* 배관작업을 한다.
* =============================================================
*/
if (f.exists()) {
int ch = JOptionPane.showConfirmDialog(this, "덮어씌우겠습니까?");
if (ch == JOptionPane.CANCEL_OPTION) {
return;
}
}
/*
* ==========================================================
* 현재행에 제어가 넘어왔다면 파일이 존재하지 않거나 존재하더라도
* 덮어씌우기를 선택한 경우이다.
* ==========================================================
*/
fos = new FileOutputStream(f);
//FileOutputStream을 통하여 파일에 쓰기
byte[] buf = new byte[2048];
int size = -1;
while((size = input.read(buf))!=-1){
fos.write(buf, 0, size);
}
JOptionPane.showMessageDialog(this, "저장완료!!");
} catch (Exception ex) {
} finally {
try {
fos.close();
} catch (IOException ex) {
}
}
}
}
}
설정
트랙백
댓글
글
JAVA 스윙 야구게임 프로그래밍
오랜전에 교육센터 있던 시절 심심해서 만들었던거 같은데...
오래전에 만든거라 지금 보면 코드가 지저분하네요...
참고용으로만 보시는게 좋을듯해요..
/*Baseball*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Baseball extends JFrame {
JMenuBar bar ;
JMenu control;
JMenuItem replay;
JMenuItem show;
JMenuItem exit;
JPanel p;
JButton submit;
JTextField tf1,tf2,tf3;
JTextArea ta;
int strike;
int ball;
int attemp;
String msg ;
int[] array;
int[] userNo;
public Baseball(){
super("Baseball Game");
init();
event();
start();
this.setSize(300, 400);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frm = super.getSize();
int xpos = (int) (screen.getWidth() / 2 -frm.getWidth() / 2);
int ypos = (int) (screen.getHeight() / 2 - frm.getHeight() / 2);
this.setLocation(xpos, ypos);
this.setVisible(true);
}
public void init(){
array = new int[3];
userNo = new int[3];
attemp =0 ;
this.setJMenuBar(bar = new JMenuBar());
this.add(p = new JPanel(),BorderLayout.NORTH);
this.add(ta = new JTextArea(),BorderLayout.CENTER);
bar.add(control = new JMenu("Control"));
control.add(replay = new JMenuItem("다시하기"));
control.add(show = new JMenuItem("정답보기"));
control.addSeparator();
control.add(exit = new JMenuItem("종료"));
p.setLayout(new FlowLayout());
p.add(new JLabel("수 : "));
p.add(tf1 = new JTextField(3));
p.add(new JLabel("수 : "));
p.add(tf2 = new JTextField(3));
p.add(new JLabel("수 : "));
p.add(tf3 = new JTextField(3));
p.add(new JLabel(" "));
p.add(submit =new JButton("확인"));
p.setBackground(Color.lightGray);
}
/*이벤트를 발생시키는 내부클래스를 초기화하는 메소드*/
public void event(){
/*확인 버튼 누를시 게임시작 및 결과출력*/
submit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
userNo[0]=Integer.parseInt(tf1.getText());
userNo[1]=Integer.parseInt(tf2.getText());
userNo[2]=Integer.parseInt(tf3.getText());
/*각 필드에 같은 번호 입력체크*/
if(userNo[0]==userNo[1] || userNo[1]==userNo[2] || userNo[2]==userNo[0]){
ta.append("각 필드에 다른 번호를 입력해주세요\n");
return;
}
strike = 0;
ball = 0;
check();
attemp++; //시도한횟수 카운트
if(strike!=0 || ball !=0){
ta.append("입력한숫자 : "+userNo[0]+" "+userNo[1]+" "+userNo[2]+" [ "+"Strike : " + strike +"개"+ " ball : " + ball+"개 ]\n");
if(strike == 3){
ta.setBackground(Color.orange);
ta.append("당신이 시도한 횟수는 :" + attemp+"번 입니다. \n");
}
}else
ta.setText(msg);
}
});
/* 종료버튼 누를시 종료되는 이벤트*/
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
/*정답보기 이벤트*/
show.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
ta.setText("포기하셨군요....ㅠ-ㅠ 정답은 : " +array[0]+array[1]+array[2]+"\n");
tf1.setText("");
tf2.setText("");
tf3.setText("");
}
});
/*게임다시 시작이벤트*/
replay.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
ta.setText("");
tf1.setText("");
tf2.setText("");
tf3.setText("");
}
});
/* 윈도우 창 종료*/
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0); //프로그램종료
}
});
}
/*시작시 랜덤하게 중복되지 않는 번호 받아오는 메소드*/
public void start(){
label:for(int i=0 ; i<array.length ; ){
array[i]=(int)(Math.random()*9+1);
for(int j=0 ;j<i ; j++){
if(array[j] == array[i])
continue label;
}
i++;
}
}
/*strike or ball 체크*/
public void check(){
for(int i = 0 ; i<array.length;i++){
for(int j = 0 ; j<array.length ; j++){
if(array[i]==userNo[j]){
if(i==j)
strike++;
else
ball++;
} //strike,ball check;
else
msg = "맞춘 숫자가 없습니다.\n";
} //inner for loop
} //outter for loop
}
public static void main(String[] args){
new Baseball();
}
}
설정
트랙백
댓글
글
Java] java.lang.reflect.* 활용
*JSP 페이지로부터 form에 대한 값을 넘겨받아 useBean을 이용해서 값 저장
- jsp action 페이지에서 값을 저장후 reflect를 사용한 클래스 호출
<jsp:useBean id="vo" class="com.bbs.BbsVO">
<jsp:setProperty name="vo" property="*"/>
</jsp:useBean>
com.util.BeanExamer.survey(vo); // 자바클래스의 reflect를 이용한 클래스
* BeanExamer.java
package com.util;
import java.lang.ref.*;
import java.lang.reflect.*; // reflect를 사용하기 위한 import
import java.util.*;
public class BeanExamer {
public static void survey(Object obj){
Class clz = obj.getClass(); // 인자로 전달받은 vo객체를 통해 클래스를 얻어냄
Method[] methods = clz.getDeclaredMethods();
// 위에서 얻어낸 클래스를 통해 해당 클래스에 선언된 메소드들을 배열에 저장
ArrayList<Method> getMethods = new ArrayList<Method>(); // ArrayList에 메소드 타입으로 제너릭 설정
for(int i = 0; i < methods.length;i++){
/* 클래스에 선언된 메서드수만큼 loof를 시키고 get으로 시작하는 메서드만 ArrayList에 저장 */
if(methods[i].getName().startsWith("get") == true){
getMethods.add(methods[i]);
}
}
if(getMethods.size() <= 0){
return;
}
for(int i = 0; i < getMethods.size() ; i++){
Method m = getMethods.get(i);
try {
System.out.println(m.invoke(obj, null)); //invoke 메소드에 관한 내용은 아래내용을 참고
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
1.원형
Object invoke( Object obj, Object[] args )
2.사용
Class myclass = Class.forName( "package.name.MyClass" ); //특정 클래스의 클래스를 가져옴
Object myclassInstance = myclass.newInstance(); // 특정 클래스의 인스턴스 생성
Method[] methods = myclass.getMethods(); // 클래스의 메소드를 가져옴
// 메소드의 매개변수를 설정. 타입에 따라 Object 배열 초기화 코드의 내용이 틀려짐.
Object[] params = new Object[] { new Integer( value ) };
methods[0].invoke( myclassInstance, params ); //invoke함수는 클래스안에 메소드를 호출하게된다.
Method 클래스의 invoke 함수의 API 입니다. 보다시피 매개변수로 첫번째 메소드를 실행시킬 인스턴스나 클래스
를 넣어줘야 하고, 그 메소드의 매개변수를 Object 배열로 넣게 된다.
따라서 인트는 new Integer()로 감싸주거나 new BigDecimal()로 감싸주어 Object형으로 캐스팅 되게끔하고
String은 그 자체로서 Obejct형으로 캐스팅 되면서 Object[]배열로서 매겨변수로 들어가데 된다.
그러면 그 함수의 매개변수에 배열의 순서대로 넣어서 실행을 시킬수 있는것이다.
RECENT COMMENT