Hazır Java Kodları - Yeni

X-Paylaşım Facebook Hayran Sayfası
11 Temmuz 2009/03:34 #1

Hazır Java Kodları - Yeni

Hazır Java Kodları - Yeni



Arkadaşlar elimde bulunan java kodlarını paylaşmak istedim.

Basit Bir Http İstemcisi Örneği

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

public class SocketCat {

public static void main(String[] args) {

for (int i = 0; i < args.length; i++) {
int port = 80;
String file = "/";
try {
URL u = new URL(args[i]);
if (u.getPort() != -1) port = u.getPort();
if (!(u.getProtocol().equalsIgnoreCase("http"))) {
System.err.println("I only understand http.");
continue;
}
if (!(u.getFile().equals(""))) file = u.getFile();
Socket s = new Socket(u.getHost(), port);
OutputStream theOutput = s.getOutputStream();
PrintWriter pw = new PrintWriter(theOutput, false);
pw.println("GET " + file + " HTTP/1.0");
pw.println("Accept: text/plain, text/html, text/*");
pw.println();
pw.flush();

InputStream in = s.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr, "ASCII");
String theLine;
while ((theLine = br.readLine()) != null) {
System.out.println(theLine);
}
}
catch (MalformedURLException e) {
System.err.println(args[i] + " is not a valid URL");
}
catch (IOException ex) {
System.err.println(ex);
}

}

}

}


-----------------------------------

Dosya Bölme İşlemi

import java.io.*;
import java.util.zip.*;

class Main {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: java Main <input> <output>");
System.exit(-1);
}
try {
FileInputStream in = new FileInputStream(args[0]);

// Create compressed stream that writes to byte array output stream
ByteArrayOutputStream b = new ByteArrayOutputStream();
GZIPOutputStream out = new GZIPOutputStream(b);

byte[] buf = new byte[512];
int howmany;
while ((howmany = in.read(buf)) > 0) {
out.write(buf, 0, howmany);
}
in.close();
out.flush();
byte[] compressedBytes = b.toByteArray(); // get byte array
b.writeTo(new FileOutputStream(args[1])); // write to file
out.close(); // closes both out and b
System.out.println("compressed size: " + compressedBytes.length);
// ... do something with byte array

} catch (IOException e) {
System.out.println(e);
}
}
}


--------------------------------

Dosya Kopyalama

import java.io.*;

public class Kopyala {

public Kopyala()
{
okuX();
}

private void okuX()
{
try {
File kopyalanan=new File("C:\\command.com");
File kopyasi=new File("D:\\" + kopyalanan.getName());

FileOutputStream yazici=new FileOutputStream(kopyasi);
FileInputStream al=new FileInputStream(kopyalanan);

int b;

System.out.print("Dosya Boyutu:" + kopyalanan.length());

while ((b=al.read())!=-1)
{
yazici.write(b);
}

}
catch (Exception e)
{
//
}
}

public static void main(String[] args)
{
Kopyala a=new Kopyala();
}
}

----------------------------------------

Dosyadan Son Satırı Silmek

import java.io.*;

public class DelLstLine{
public static void main(String[] arg){
try{
RandomAccessFile raf = new RandomAccessFile("RandFile.txt", "rw");
long length = raf.length();
System.out.println("File Length="+raf.length());
//supposing that last line is of 8
raf.setLength(length - 8);
System.out.println("File Length="+raf.length());
raf.close();
}catch(Exception ex){
ex.printStackTrace();
}
}//end of psvm
}//class ends

---------------------------------

Dosyaya Yazmak

import java.io.*;

class Yaz
{
public static void main(String[] args)
{
try
{
FileOutputStream streamNesne = new FileOutputStream("Yeni Klasör\\tekstdosyasi.txt");
//FileOutputStream streamNesne = new FileOutputStream("c:\\Documents and Settings\\numan\\Desktop\\Yeni Klasör\\tekstdosyasi.txt");

PrintWriter yazdirici = new PrintWriter(streamNesne);

String satir="Merhaba Sevgili Okurlar, ";

yazdirici.println(satir);
yazdirici.close();

System.out.println("Dilemis oldugunuz \"" + satir + "\" satiri ilgili dosyaya yazdirildi. ");
}

catch (FileNotFoundException excep)
{
System.out.println("Bu isimde bir dosya bulunamadi ...");
}
catch (IOException excep)
{
System.out.println("Bir \"exception\" olustu ...");
}

}
}


----------------------

Dosyayı Kesip, Başka Yere Yapıştırmak

public static void main(String args[]){
try{
// File (or directory) to be moved
File file = new File("file.txt");

// Destination directory
File dir = new File("gg");

// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
System.out.println("File moved");
}
}
catch (Exception ioe){
ioe.printStackTrace();
}
}


-----------------------------

Etiketi Sürüklemek

CTRL tu?una basyly tutarak, fare ile etiketi sürükleyin!

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class MoveLabel extends JFrame
{
JLabel label;
public MoveLabel()
{
label = new JLabel(new ImageIcon("copy.gif"));
label.setBounds(20,30,16,19);
label.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode() == KeyEvent.VK_DOWN)
{
label.setLocation(label.getX(),label.getY()+1);
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_UP)
{
label.setLocation(label.getX(),label.getY()-1);
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_LEFT)
{
label.setLocation(label.getX()-1,label.getY());
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_RIGHT)
{
label.setLocation(label.getX()+1,label.getY());
repaint();
}
}
});
label.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
if(me.getClickCount() == 1)
{
boolean dd = label.isOptimizedDrawingEnabled();
boolean ff = label.requestFocusInWindow();
repaint();
}
}

});
JPanel p = new JPanel();
p.setPreferredSize(new Dimension(2000,1000));
p.setLayout(null);
p.add(label);
JScrollPane js = new JScrollPane(p);
getContentPane().add(js);
}
public static void main(String args[])
{
MoveLabel frame = new MoveLabel();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setSize(300,300);
frame.setVisible(true);
}
}


-------------------
11 Temmuz 2009/03:35 #2
Fareyi Kullanarak Resim Çizmek


public class MousePaint extends Frame implements MouseMotionListener
{
private int x1, y1, x2, y2;
public MousePaintII()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
dispose();
System.exit(0);
}
});
addMouseMotionListener(this);
setBounds(50,50,400,250);
setVisible(true);
}
public static void main(String[] argv)
{
new MousePaintII();
}
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
g.setColor(Color.black);
g.drawLine(x1, y1, x2, y2);
}
public void mouseDragged(MouseEvent me)
{
me.consume();
int x = me.getX();
int y = me.getY();
if ( x1 == 0 )
{
x1 = x;
}
if ( y1 == 0 )
{
y1 = y;
}
x2 = x;
y2 = y;
repaint();
x1 = x2;
y1 = y2;
}
public void mouseMoved(MouseEvent me)
{ }
}


----------------------------------------------------------------------


FileServer


import java.net.*;
import java.io.*;
import java.util.*;

public class FileServer
{
public static void main(String[] args)
{
// read arguments
if (args.length!=2) {
System.out.println("Usage: java FileServer <port> <wwwhome>");
System.exit(-1);
}
int port = Integer.parseInt(args[0]);
String wwwhome = args[1];

// open server socket
ServerSocket socket = null;
try {
socket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not start server: " + e);
System.exit(-1);
}
System.out.println("FileServer accepting connections on port " + port);

// request handler loop
while (true) {
Socket connection = null;
try {
// wait for request
connection = socket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
OutputStream out = new BufferedOutputStream(connection.getOutputStream()) ;
PrintStream pout = new PrintStream(out);

// read first line of request (ignore the rest)
String request = in.readLine();
if (request==null)
continue;
log(connection, request);
while (true) {
String misc = in.readLine();
if (misc==null || misc.length()==0)
break;
}

// parse the line
if (!request.startsWith("GET") || request.length()<14 ||
!(request.endsWith("HTTP/1.0") || request.endsWith("HTTP/1.1"))) {
// bad request
errorReport(pout, connection, "400", "Bad Request",
"Your browser sent a request that " +
"this server could not understand.");
} else {
String req = request.substring(4, request.length()-9).trim();
if (req.indexOf("..")!=-1 ||
req.indexOf("/.ht")!=-1 || req.endsWith("~")) {
// evil hacker trying to read non-wwwhome or secret file
errorReport(pout, connection, "403", "Forbidden",
"You don't have permission to access the requested URL.");
} else {
String path = wwwhome + "/" + req;
File f = new File(path);
if (f.isDirectory() && !path.endsWith("/")) {
// redirect browser if referring to directory without final '/'
pout.print("HTTP/1.0 301 Moved Permanently\r\n" +
"Location: http://" +
connection.getLocalAddress().getHostAddress() + ":" +
connection.getLocalPort() + "/" + req + "/\r\n\r\n");
log(connection, "301 Moved Permanently");
} else {
if (f.isDirectory()) {
// if directory, implicitly add 'index.html'
path = path + "index.html";
f = new File(path);
}
try {
// send file
InputStream file = new FileInputStream(f);
pout.print("HTTP/1.0 200 OK\r\n" +
"Content-Type: " + guessContentType(path) + "\r\n" +
"Date: " + new Date() + "\r\n" +
"Server: FileServer 1.0\r\n\r\n");
sendFile(file, out); // send raw file
log(connection, "200 OK");
} catch (FileNotFoundException e) {
// file not found
errorReport(pout, connection, "404", "Not Found",
"The requested URL was not found on this server.");
}
}
}
}
out.flush();
} catch (IOException e) { System.err.println(e); }
try {
if (connection != null) connection.close();
} catch (IOException e) { System.err.println(e); }
}
}

private static void log(Socket connection, String msg)
{
System.err.println(new Date() + " [" + connection.getInetAddress().getHostAddress() +
":" + connection.getPort() + "] " + msg);
}

private static void errorReport(PrintStream pout, Socket connection,
String code, String title, String msg)
{
pout.print("HTTP/1.0 " + code + " " + title + "\r\n" +
"\r\n" +
"<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n" +
"<TITLE>" + code + " " + title + "</TITLE>\r\n" +
"</HEAD><BODY>\r\n" +
"<H1>" + title + "</H1>\r\n" + msg + "<P>\r\n" +
"<HR><ADDRESS>FileServer 1.0 at " +
connection.getLocalAddress().getHostName() +
" Port " + connection.getLocalPort() + "</ADDRESS>\r\n" +
"</BODY></HTML>\r\n");
log(connection, code + " " + title);
}

private static String guessContentType(String path)
{
if (path.endsWith(".html") || path.endsWith(".htm"))
return "text/html";
else if (path.endsWith(".txt") || path.endsWith(".java"))
return "text/plain";
else if (path.endsWith(".gif"))
return "image/gif";
else if (path.endsWith(".class"))
return "application/octet-stream";
else if (path.endsWith(".jpg") || path.endsWith(".jpeg"))
return "image/jpeg";
else
return "text/plain";
}

private static void sendFile(InputStream file, OutputStream out)
{
try {
byte[] buffer = new byte[1000];
while (file.available()>0)
out.write(buffer, 0, file.read(buffer));
} catch (IOException e) { System.err.println(e); }
}
}
11 Temmuz 2009/03:36 #3
FTP İstemcisi


import java.io.*;
import java.net.*;
import java.util.*;

public class TestFTP
{

public static void main(String args[])
{
try {
SimpleFTP ftp = new SimpleFTP();

// Connect to an FTP server on port 21.
System.out.println ("connecting...");
ftp.connect("mail.baskent.edu.tr", 21, "kullanycy_ad", "sifre");

// Set binary mode.
ftp.bin();

// Change to a new working directory on the FTP server.
ftp.cwd("web");

// Upload some files.
ftp.stor(new File("webcam.jpg"));
ftp.stor(new File("comicbot-latest.png"));
// You can also upload from an InputStream, e.g.
//ftp.stor(new FileInputStream(new File("test.png")), "test.png");
//ftp.stor(someSocket.getInputStream(), "blah.dat");

// Quit from the FTP server.
ftp.disconnect();

}
catch (IOException e) {
// Jibble.
}

}

}


----------------------------------------------------------------

FTP Sunucusu


SimpleFTP.java:

import java.io.*;
import java.net.*;
import java.util.*;

public class SimpleFTP {


/**
* Create an instance of SimpleFTP.
*/
public SimpleFTP() {

}


/**
* Connects to the default port of an FTP server and logs in as
* anonymous/anonymous.
*/
public synchronized void connect(String host) throws IOException {
connect(host, 21);
}


/**
* Connects to an FTP server and logs in as anonymous/anonymous.
*/
public synchronized void connect(String host, int port) throws IOException {
connect(host, port, "anonymous", "anonymous");
}


/**
* Connects to an FTP server and logs in with the supplied username
* and password.
*/
public synchronized void connect(String host, int port, String user, String pass) throws IOException {
if (socket != null) {
throw new IOException("SimpleFTP is already connected. Disconnect first.");
}
socket = new Socket(host, port);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

String response = readLine();
if (!response.startsWith("220 ")) {
throw new IOException("SimpleFTP received an unknown response when connecting to the FTP server: " + response);
}

sendLine("USER " + user);

response = readLine();
if (!response.startsWith("331 ")) {
throw new IOException("SimpleFTP received an unknown response after sending the user: " + response);
}

sendLine("PASS " + pass);

response = readLine();
if (!response.startsWith("230 ")) {
throw new IOException("SimpleFTP was unable to log in with the supplied password: " + response);
}

// Now logged in.
}


/**
* Disconnects from the FTP server.
*/
public synchronized void disconnect() throws IOException {
try {
sendLine("QUIT");
}
finally {
socket = null;
}
}


/**
* Returns the working directory of the FTP server it is connected to.
*/
public synchronized String pwd() throws IOException {
sendLine("PWD");
String dir = null;
String response = readLine();
if (response.startsWith("257 ")) {
int firstQuote = response.indexOf('\"');
int secondQuote = response.indexOf('\"', firstQuote + 1);
if (secondQuote > 0) {
dir = response.substring(firstQuote + 1, secondQuote);
}
}
return dir;
}


/**
* Changes the working directory (like cd). Returns true if successful.
*/
public synchronized boolean cwd(String dir) throws IOException {
sendLine("CWD " + dir);
String response = readLine();
return (response.startsWith("250 "));
}


/**
* Sends a file to be stored on the FTP server.
* Returns true if the file transfer was successful.
* The file is sent in passive mode to avoid NAT or firewall problems
* at the client end.
*/
public synchronized boolean stor(File file) throws IOException {
if (file.isDirectory()) {
throw new IOException("SimpleFTP cannot upload a directory.");
}

String filename = file.getName();

return stor(new FileInputStream(file), filename);
}


/**
* Sends a file to be stored on the FTP server.
* Returns true if the file transfer was successful.
* The file is sent in passive mode to avoid NAT or firewall problems
* at the client end.
*/
public synchronized boolean stor(InputStream inputStream, String filename) throws IOException {

BufferedInputStream input = new BufferedInputStream(inputStream);

sendLine("PASV");
String response = readLine();
if (!response.startsWith("227 ")) {
throw new IOException("SimpleFTP could not request passive mode: " + response);
}

String ip = null;
int port = -1;
int opening = response.indexOf('(');
int closing = response.indexOf(')', opening + 1);
if (closing > 0) {
String dataLink = response.substring(opening + 1, closing);
StringTokenizer tokenizer = new StringTokenizer(dataLink, ",");
try {
ip = tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken();
port = Integer.parseInt(tokenizer.nextToken()) * 256 + Integer.parseInt(tokenizer.nextToken());
}
catch (Exception e) {
throw new IOException("SimpleFTP received bad data link information: " + response);
}
}

sendLine("STOR " + filename);

Socket dataSocket = new Socket(ip, port);

response = readLine();
if (!response.startsWith("150 ")) {
throw new IOException("SimpleFTP was not allowed to send the file: " + response);
}

BufferedOutputStream output = new BufferedOutputStream(dataSocket.getOutputStream()) ;
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
output.flush();
output.close();
input.close();

response = readLine();
return response.startsWith("226 ");
}


/**
* Enter binary mode for sending binary files.
*/
public synchronized boolean bin() throws IOException {
sendLine("TYPE I");
String response = readLine();
return (response.startsWith("200 "));
}


/**
* Enter ASCII mode for sending text files. This is usually the default
* mode. Make sure you use binary mode if you are sending images or
* other binary data, as ASCII mode is likely to corrupt them.
*/
public synchronized boolean ascii() throws IOException {
sendLine("TYPE A");
String response = readLine();
return (response.startsWith("200 "));
}


/**
* Sends a raw command to the FTP server.
*/
private void sendLine(String line) throws IOException {
if (socket == null) {
throw new IOException("SimpleFTP is not connected.");
}
try {
writer.write(line + "\r\n");
writer.flush();
if (DEBUG) {
System.out.println("> " + line);
}
}
catch (IOException e) {
socket = null;
throw e;
}
}

private String readLine() throws IOException {
String line = reader.readLine();
if (DEBUG) {
System.out.println("< " + line);
}
return line;
}

private Socket socket = null;
private BufferedReader reader = null;
private BufferedWriter writer = null;

private static boolean DEBUG = false;


}
11 Temmuz 2009/03:36 #4
Java Diyalog Örneği


/*
This applet demonstrates four easy-to-use routines for
showing a dialog box and, in three cases, getting back
some information from the user. The methods are:

JOptionPane.showMessageDialog
JOptionPane.showConfirmDialog
JOptionPane.showInputDialog
JColorChooser.showDialog
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SimpleDialogDemo extends JApplet implements ActionListener {

JLabel message; // A label for giving some feedback to the user.
// It appears at the top of the applet.

Color selectedColor = Color.gray; // This color will be used as the
// initial color in the color chooser.
// It is used to rememeber the user's
// color choice, so that the color
// chooser can show the same color,
// if it is opened twice.


public void init() {
// Set up the applet with a message label and four buttons.
// Each button will open a different type of dialog.

setBackground(Color.gray);
getContentPane().setBackground(Color.gray);
getContentPane().setLayout( new GridLayout(3,1,3,3) );
message = new JLabel("Click a button to open a dialog", JLabel.CENTER);
message.setForeground(new Color(180,0,0));
message.setBackground(Color.white);
message.setOpaque(true);
getContentPane().add(message);

JPanel buttonBar;
JButton button;

buttonBar = new JPanel();
buttonBar.setLayout(new GridLayout(1,2,3,3));
buttonBar.setBackground(Color.gray);
getContentPane().add(buttonBar);
button = new JButton("Message Dialog");
button.addActionListener(this);
buttonBar.add(button);
button = new JButton("Confirm Dialog");
button.addActionListener(this);
buttonBar.add(button);

buttonBar = new JPanel();
buttonBar.setLayout(new GridLayout(1,2,3,3));
buttonBar.setBackground(Color.gray);
getContentPane().add(buttonBar);
button = new JButton("Input Dialog");
button.addActionListener(this);
buttonBar.add(button);
button = new JButton("Color Chooser");
button.addActionListener(this);
buttonBar.add(button);

} // end init()


public Insets getInsets() {
// Leave a gray border around the applet.
return new Insets(3,3,3,3);
}


public void actionPerformed(ActionEvent evt) {
// Respond to a button click by showing a dialog
// and setting the message label to describe the
// user's response.

String command = evt.getActionCommand();

if (command.equals("Message Dialog")) {
message.setText("Displaying message dialog.");
JOptionPane.showMessageDialog(null,
"This is an example of JOptionPane.showMessageDialog.");
message.setText("You closed the message dialog.");
}

else if (command.equals("Confirm Dialog")) {
message.setText("Displaying confirm dialog.");
int response = JOptionPane.showConfirmDialog(null,
"This is an example of JOptioPane.showConfirmDialog.\n"
+ "Click any button to indicate your response.");
switch(response) {
case JOptionPane.YES_OPTION:
message.setText("You clicked \"Yes\".");
break;
case JOptionPane.NO_OPTION:
message.setText("You clicked \"No\".");
break;
case JOptionPane.CANCEL_OPTION:
message.setText("You clicked \"Cancel\".");
break;
case JOptionPane.CLOSED_OPTION:
message.setText("You closed the box without making a selection.");
}
}

else if (command.equals("Input Dialog")) {
message.setText("Displaying input dialog.");
String response = JOptionPane.showInputDialog(null,
"This is an example of JOptioPane.showInputDialog.\n"
+ "Type your response, and click a button.");
if (response == null)
message.setText("You canceled the input.");
else if (response.trim().length() == 0)
message.setText("You left the input box empty.");
else
message.setText("You entered \"" + response + "\".");
}

else if (command.equals("Color Chooser")) {
message.setText("Displaying color chooser dialog.");
Color c = JColorChooser.showDialog(null,"Select a Color",selectedColor);
if (c == null)
message.setText("You canceled without selecting a color.");
else {
selectedColor = c; // Remember selected color for next time.
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
message.setText("You selected RGB = (" + r + "," + g + "," + b + ").");
}
}

} // end actionPerformed()


} // end class SimpleDialogDemo

Benzer Konular

JAVA kategorisindeki Hazır Java Kodları - Yeni konusuna benzer yazılar. Hazır Java Kodları - Yeni yazısını beğendiyseniz belki bu konular da ilginizi çekebilir.


Zaman: GMT +4 Saat:09:47

©2005 - 2009 X-Paylasim.com - Genel eğlence ve bilgi paylaşım platformu. SimpleX vBulletin Theme
Web Dizini Powered by vBulletin® Version Copyright ©2000 - 2009, Jelsoft Enterprises Ltd. SEO by vBSEO 3.3.1 1 2
film indir grup reyting