[ 무료 ] 웹툰 , 이상한 것들

2008년 8월 7일 목요일

자바 다중파일 전송




import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.io.*;
import javax.swing.border.*;
import javax.swing.table.DefaultTableModel;

import java.net.*;
import java.io.FileNotFoundException;

public class FileSendClient extends JFrame implements ActionListener{
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JLabel l = new JLabel("보낼파일");
JTextField tf = new JTextField(20);
FileDialog fd;
JButton b1,b2;
String directory="", file="";
DefaultTableModel model;
int fileN=0;// 추가 성택파일수

/* 아시죠? 프레임을 구성할 컴포넌트들 생성함 */
public FileSendClient() throws Exception{
this.setLayout(null);
//추가 JTable
JTable table = new JTable(model = new DefaultTableModel(null, new String[]{"1","2"}));

b1=new JButton("파일선택");
b1.addActionListener(this);
b2=new JButton("파일전송");
b2.addActionListener(this);

p1.add(b1);
add(p1);
p2.add(b2);
add(p2);
p3.add(l);
p3.add(tf);
add(p3);
//추가
p4.add(table);
add(p4);

p1.setBounds(70,70,100,100);
p2.setBounds(200,70,100,100);
p3.setBounds(0,15,340,30);
p4.setBounds(20,130,200,200); //추가

setSize(new Dimension(350, 250));
setVisible(true);
//setResizable(false);
setTitle("파일전송");

}

/* 버튼에 액션 발생시 실행됨 */
public void actionPerformed(ActionEvent ae){

try{

/* 파일선택 다이얼 로그가 뜨고 */
if(ae.getActionCommand().equals("파일선택")){
fd=new FileDialog(this,"파일선택",FileDialog.LOAD);/*Load = 파일읽기 작업용*/
fd.setVisible(true);
tf.setText("");

/* 선택했을 경우 디렉토리와 파일명이 저장됨 */

directory=fd.getDirectory();
file=fd.getFile();
tf.setText(directory+file);
//추가 선택 파일 table에 추가
model.addRow(new Object[]{String.valueOf(++fileN), directory+file});


/* "else" 파일전송버튼 클릭시 실행됨 */
}else{
// 추가 table의 fileN 파일이름으로 전송
for(int i=0;i<fileN;i++){
String fName=(String) model.getValueAt(i, 1);
System.out.println(fName );


/* localhost 부분은 상대편 ip 주소를 입력하고, 3333 은 서버측 포트와 동일하게 세팅 */
Socket s=new Socket("localhost", 3333);

/* 소켓으로부터 OutputStream 얻어서 파일명을 먼저 보냄 */

/* 서버측에서 파일 객체 생성시 이용할 것임 */

BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
// System.out.println("파일명 : "+file);
// bw.write(file+"\n"); bw.flush();
//file 대신에 fName 이거 사용하세요.
System.out.println("파일명 : "+fName);
bw.write(fName+"\n"); bw.flush();

/* 선택한 파일로 부터 스트림을 읽어들여서 얻어놓은 OutputStream에 연결 */
DataInputStream dis=new DataInputStream(new FileInputStream(new File(tf.getText())));
DataOutputStream dos=new DataOutputStream(s.getOutputStream());


/* 바이트단위로 읽어서 스트림으로 쓰기 */


/* 자원정리 */
int b=0;
while( (b=dis.read()) != -1 ){
dos.writeByte(b); dos.flush();
}


/* 자원정리 */

dis=null; dos=null; s=null;

}

System.exit(1);
}
}catch(Exception e){
System.out.println(e);
}
}

/* 메인 */
public static void main(String args[]) throws Exception{

new FileSendClient();
}
}

//새로추가---------------------------------

다중 파일 전송 프로그램을 Java로 구현하는 방법은 여러 가지가 있습니다. 그러나 대표적인 방법 중 하나는 Java의 Socket API를 사용하여 구현하는 것입니다. 이를 위해서는 서버-클라이언트 모델을 따르는 코드를 작성해야 합니다.

아래는 서버-클라이언트 모델을 따르는 Java 코드 예시입니다.

서버 코드:

import java.io.*; import java.net.*; public class FileServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(1234); // 포트번호 1234 사용 while (true) { Socket socket = serverSocket.accept(); // 클라이언트 요청 대기 DataInputStream inputStream = new DataInputStream(socket.getInputStream()); int numFiles = inputStream.readInt(); // 클라이언트가 보낸 파일 개수 for (int i = 0; i < numFiles; i++) { String filename = inputStream.readUTF(); // 클라이언트가 보낸 파일 이름 long filesize = inputStream.readLong(); // 클라이언트가 보낸 파일 크기 FileOutputStream fileOutputStream = new FileOutputStream(filename); byte[] buffer = new byte[4096]; int read = 0; long totalRead = 0; long remaining = filesize; while ((read = inputStream.read(buffer, 0, (int) Math.min(buffer.length, remaining))) > 0) { totalRead += read; remaining -= read; fileOutputStream.write(buffer, 0, read); } fileOutputStream.close(); } inputStream.close(); socket.close(); } } }

클라이언트 코드:
import java.io.*;
import java.net.*; import java.util.ArrayList; public class FileClient { public static void main(String[] args) throws IOException { Socket socket = new Socket("localhost", 1234); // 로컬호스트, 포트번호 1234 DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream()); outputStream.writeInt(args.length); // 보낼 파일 개수 전송 for (String filename : args) { File file = new File(filename); outputStream.writeUTF(file.getName()); // 파일 이름 전송 outputStream.writeLong(file.length()); // 파일 크기 전송 FileInputStream fileInputStream = new FileInputStream(file); byte[] buffer = new byte[4096]; int read; while ((read = fileInputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, read); } fileInputStream.close(); } outputStream.close(); socket.close(); } }

위 코드를 실행하면, 서버는 클라이언트로부터 파일을 전송받아 해당 파일들을 저장하고, 클라이언트는 서버로 파일을 전송합니다. 클라이언트는 다음과 같이 실행할 수 있습니다.

java FileClient file1.txt file2.txt file3.txt

위 예시에서는 서버와 클라이언트가 같은 호스트에서 실행되는 것으로 가정합니다.


자바 다중파일 전송

2008년 8월 6일 수요일

java Random





import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.*;

public class Coin implements ActionListener {
static JLabel label;
public static void main(String[] args){
JFrame frame = new JFrame("Coin Program");
frame.setPreferredSize(new Dimension(200,120));
frame.setLocation(500,400);
Container contentPane = frame.getContentPane();
JButton button = new JButton("코인 던지기");
label = new JLabel(" ");
contentPane.add(button,BorderLayout.CENTER);
contentPane.add(label,BorderLayout.SOUTH);
Coin listener = new Coin();
button.addActionListener(listener);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
int f=0,b=0;
Random oRandom = new Random();
for(int i= 0;i<77;i++){
// 1~77까지의 정수를 랜덤하게 출력
int r = oRandom.nextInt(77) + 1;
//앞뒤판단
if(r%2==0)f++;
else b++;

}
label.setText("앞: "+f+"뒷: "+b);
}
}

//의문점 쪽지 주세요

2008년 8월 3일 일요일

ex8



public class ex8 {
//배열 inex가 하나더 필요하고요.
static int index = 0,indexName=0;
static int startAccountNumbers = 123;
// static int [] accountNumbers = new int [5];
// static double [] accountBalances = new double [5];
// static String [] firstNames = new String [5];
// static String [] lastNames = new String [5];
// static boolean [] creditCards = new boolean [5];
//원래는 클래스로 묶고 벡터를 사용해야 하는데

//여기하고
//"indexName"
static int [] accountNumbers = new int [50];
static double [] accountBalances = new double [50];
static String [] states = new String [50];


//여기는 다르게 생각하고요.
//"index"
static String [] firstNames = new String [50];
static String [] lastNames = new String [50];
static boolean [] creditCards = new boolean [50];
static double [] accountBalancesSum = new double [50];


public static void main (String [] args) {//메인에 있는것은 무조건 들어가야하는거입니다.

createNewCustomer ();

createNewCustomer ();

createNewCustomer ();


makeDeposit (1539.28, 123);

makeDeposit (-483,123);

makeWithdrawal (399.99, 123);


makeDeposit (333.50, 369);

makeDeposit (400, 369);

makeDeposit (512.99, 369);

makeWithdrawal (250, 369);


makeWithdrawal (200, 1107);

makeDeposit (200, 1107);

makeWithdrawal (-800000,1107);

makeWithdrawal (200, 1107);


makeWithdrawal (1000, 3443);

makeDeposit (14.92, 93939);

printAllAccounts ();

}

public static void createNewCustomer () {

firstNames [indexName] = JOptionPane.showInputDialog ("Enter new customer's first name:");

lastNames [indexName] = JOptionPane.showInputDialog ("Enter new customer's last name:");

accountNumbers [indexName]= startAccountNumbers;

startAccountNumbers = startAccountNumbers * 3;

accountBalances [indexName] = 0;

creditCards [indexName] = false;

indexName = startAccountNumbers /(3*123);

}

public static void printAccount (int index) {
int tempInedx;
for (int i = 0; i < index; i++) {

tempInedx = accountNumbers[i]/(3*123);
if(tempInedx>=0 && tempInedx<=50 && firstNames [tempInedx]!=null){

accountBalancesSum[tempInedx]=accountBalancesSum[tempInedx]+accountBalances[i];
if (accountBalancesSum[tempInedx] < 1000) {

creditCards [tempInedx] = false;

} else {

creditCards [tempInedx] = true;

}

if (accountBalancesSum[tempInedx] > -1) {

System.out.println ("$" + accountBalancesSum[tempInedx] + states[i] + " to account number: " + accountNumbers[i]);

System.out.println ("Account number: "+ accountNumbers [i]);

System.out.println ("Name: " + lastNames [tempInedx] + ", " + firstNames [tempInedx]);

System.out.println ("Account balance: $" + accountBalancesSum[tempInedx]);

if (creditCards [i] == true) {

System.out.println ("Credit card: Yes\n" );

} else {

System.out.println ("Credit card: No\n" );

}

} else {

//System.out.println ("Deposits must be greater than zero!\n");

}

}else{System.out.println("Account number "+ accountNumbers[i]+" not found!");}

}//for
}

public static void printAllAccounts () {

printAccount (index);

System.out.println ("*** Summary of Accounts ***");

}

public static void makeDeposit (double amount, int accountNumber) {

accountBalances [index] = amount;
accountNumbers [index] = accountNumber;
states[index] = " deposited";
index++;


}

public static void makeWithdrawal(double amount, int accountNumber) {

accountBalances [index] = amount;
accountNumbers [index] = accountNumber;
states [index] = " withdrawn";
index++;



}

}//main





문]
시험이 다음주라 선생님 추천의 문제 풀고있는데 잘 안풀려서요.


2008년 7월 31일 목요일

java HTML Parsing & ParserCallback


import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.HTML;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.parser.ParserDelegator;


public class HTMLParsing {
private static FileWriter writer;
//파서는 콜백 형식으로 되어 있다. 각 태그가 들어 올때 적절한 메소드가 호출됨
private class CallbackHandler extends HTMLEditorKit.ParserCallback {

//태그가 시작할 때 호출 되는 메소드
public void handleStartTag(HTML.Tag tag, MutableAttributeSet a, int pos) {

//<A href 인 경우... A태그를 찾는다...
if (tag == HTML.Tag.A) {
System.out.println(a.getAttribute(javax.swing.text.html.HTML.Attribute.HREF));
}
}

//텍스트가 들어올때 호출되는 메소드
public void handleText(char[] data, int pos) {
System.out.println(data);
try {
//텍스트만 파일에 저장합니다.
writer.write(data);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}



public void parse(String str) {
String content = null;

try {

//입력받은 URL에 연결하여 InputStream을 통해 읽은 후 파싱 한다.
// URL url = new URL(str);
//
// HttpURLConnection con = (HttpURLConnection)url.openConnection();
//
// InputStreamReader reader = new InputStreamReader(con.getInputStream(),"euc-kr");
// 여기를 수정하시면 되고요.
// 의문점 부담없이 쪽지 주세요.
InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(str)),"euc-kr");

new ParserDelegator().parse(reader, new CallbackHandler(), true);
//
// con.disconnect();
}
catch(Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) throws IOException {
//저장파일 만들고
writer = new FileWriter("c:/temp/output.txt");

HTMLParsing parser = new HTMLParsing();
parser.parse("c:/temp/aa.txt");
//파일닫는다.
writer.close();
}
}




문]
아래소스가 있습니다.
밑의 소스는
URL주소를 명령행 인자로 넣으시면 그 URL주소의 소스를 긁어와서 필요없는 태그들을 제거하고 필요한 내용만
남기고 저장하는 소스인데요,^^
저는 URL주소를 명령행인자로 줘서 URL소스를 긁어오는것이 아니라,
미리 준비되어 있는 txt파일을 불러와서 파싱하고 싶습니다.
C:\TEMP\aa.txt
탬프폴더 안에 있는 aa.txt파일을 불러와서 파싱하고 싶은데....
Input,output,,..stream의 개념이 제대로 없는건지....책을 읽고 이것저것 시도해봤는데 안되네요-_-;;;
고수님들 제발 도와주세요.................ㅠㅠ
밑의 소스는 일단 파싱은 알아서 해주니 그부분 말고
저장되어 있는 텍스트파일(소스) 불러와서 새로 다시 다른이름으로 저장하고 싶습니다..ㅠㅠ
어떻게 하면되나요??
꼭 좀 도와주십쇼...
부탁드립니다.


-


Sidewinder


World


FishMusic


LaughingBaby