java2022. 5. 14. 18:04

 

		
        String path = "C:\\Users\\Lee\\eclipse-workspace\\TestApplication\\output.txt";
        
        File file = new File(path);
		PrintStream ps = new PrintStream(new FileOutputStream(file));
        
		System.setOut(ps);

 

출처 : https://nabiro.tistory.com/252

Posted by easy16
java2022. 4. 25. 11:42

 

 

A. 라인단위로 입력이 처리되므로, 개행이 될 때마다 StringTokenizer를 새로 만드는 것에 주의

B. Integer.parseInt(br.readLine())

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.util.StringTokenizer;

public class Main {

	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());

		int N = Integer.parseInt(st.nextToken());

		/* A 
		for (int i = 0; i < N; ++i) {
			st = new StringTokenizer(br.readLine());
			int a = Integer.parseInt(st.nextToken());
			int b = Integer.parseInt(st.nextToken());
			System.out.printf("%d %d\n", a, b);
		}
		*/
        //B
        for (int i = 0; i < N; ++i) {			
			int a = Integer.parseInt(br.readLine());
			int b = Integer.parseInt(br.readLine());
			System.out.printf("%d %d\n", a, b);
		}
        
		

		br.close();

	}

}

ex)
4 
1 2
3 4
5 6
7 8

1 2
3 4
5 6
7 8

 

출처 : https://codechasseur.tistory.com/83

'java' 카테고리의 다른 글

출력을 File로 저장  (0) 2022.05.14
코테 유용한 함수 모음 (JAVA)  (0) 2022.01.08
try with resource 구문 예제 (JAVA 7)  (0) 2019.09.24
Simple UDP server & client socket 예제  (0) 2019.09.22
Simple server & client socket 예제  (0) 2019.09.22
Posted by easy16
java2022. 1. 8. 16:47

코테 유용한 함수 모음

 

HashMap<Character,Integer> hm = new HashMap<>();
HashMap<Character,Integer> em = new HashMap<>();

#ex1, 값 얻어오기(default값 지정)
hm.getOrDefault(x, 0);

/*ex2, hashmap의 비교, Sliding window 문제를 해결할 때 유용함. 
설명 :Compares the specified object with this map for equality.  Returns
     {@code true} if the given object is also a map and the two maps
     represent the same mappings.
 */
hm.equals(em);
//ex3) 중복없는 정렬된 리스트가 필요한 경우, TreeSet 사용, 기본 내림차순이므로, 필요한경우 descendingSet() 메소드를 통해 새로운 TreeSet을 리턴 받는다. 
 TreeSet<Integer> hs = new TreeSet<>();
new ArrayList(hs.descendingSet());

 

or 

 

 TreeSet<Integer> hs = new TreeSet<>(Collections.reverseOrder());

'java' 카테고리의 다른 글

출력을 File로 저장  (0) 2022.05.14
BufferedReader + StringTokenizer 예제  (0) 2022.04.25
try with resource 구문 예제 (JAVA 7)  (0) 2019.09.24
Simple UDP server & client socket 예제  (0) 2019.09.22
Simple server & client socket 예제  (0) 2019.09.22
Posted by easy16
java2019. 9. 24. 23:15


try with resource 구문 예제

ex)







public class Java7Test {



	

	public Java7Test() {

		

		this.tryWithResource();

	}

	private void tryWithResource() {

		

		String fullPath = "C:"+File.separator+"Users"+File.separator+"Lee"+File.separator+"test"+File.separator+"nio.txt";

		//Closeable을 구현한 객체는 close()를 호출하지 않아도 알아서 해제해 준다.

		try(Scanner scanner = new Scanner(new File(fullPath))) {

			System.out.println(scanner.nextLine());

			

		}catch(  NullPointerException | IOException e){

			//catch문 내에 예외 처리문이 같은 예외들을 Pipe로 묶어 한번에 처리 가능하다.

			

			e.printStackTrace();

		}

		

	

	}

	

}



 

출처 : 자바의 신

'java' 카테고리의 다른 글

BufferedReader + StringTokenizer 예제  (0) 2022.04.25
코테 유용한 함수 모음 (JAVA)  (0) 2022.01.08
Simple UDP server & client socket 예제  (0) 2019.09.22
Simple server & client socket 예제  (0) 2019.09.22
Buffer class의 이해  (0) 2019.09.22
Posted by easy16
java2019. 9. 22. 23:07

Simple UDP server & client socket 예제

DatagramSocket 및 DatagramPacket 사용법만 기억

 

ex)



public class DatagramTest {

	
	
	public DatagramTest() {
		super();
		
		new Thread() {
			public void run() {
				startUDPServer();
			}

		}.start();
		
		new Thread() {
			public void run() {
				startUDPClient();
			}

		}.start();
		
	}

	private void startUDPServer() {
		DatagramSocket server = null;
		try {
			
			server = new DatagramSocket(9999);//server 생성
			int bufferLength = 256;
			byte[] buffer = new byte[bufferLength];
			DatagramPacket packet //data 받기 위한 객체를 buffer와 length 크기를 byte 배열로 지정하여 생성
				= new DatagramPacket(buffer, bufferLength);
			while(true) {
				System.out.println("server : waiting for request.");
				server.receive(packet);
				int dataLength = packet.getLength();
				System.out.println("server : received. Data length : "+ dataLength);
				
				//get byte from packet and get it string
				String data = new String(packet.getData(), 0 , dataLength);//
				System.out.println("received data : "+data);
				
				if( data.equals("EXIT")) {
					System.out.println("stop datagram server");
					break;
				}
				
				
			}
			System.out.println("--------------");
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(server != null)
				server.close();				
		}
		
	}
	
	private void startUDPClient() {
		
		for (int loop= 0 ; loop < 3 ; loop++) {
			sendDatagramData("I hate UPD : "+ new Date());
		}
		sendDatagramData("EXIT");
	}

	private void sendDatagramData(String data) {
		try {
			DatagramSocket client = new DatagramSocket();
			/*받을 서버 지정*/
			InetAddress address = InetAddress.getByName("127.0.0.1");
			
			//byte array로 변환
			byte[ ] buffer = data.getBytes();
			
			
			//DatagramPacket 생성 및 포트 지정.
			DatagramPacket packet
			= new DatagramPacket(buffer, 0 , buffer.length, address, 9999);
			
			client.send(packet);
			
			System.out.println("Client: send Data");
			client.close();
			
			Thread.sleep(1000);
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
}

출처 : 자바의 신

'java' 카테고리의 다른 글

코테 유용한 함수 모음 (JAVA)  (0) 2022.01.08
try with resource 구문 예제 (JAVA 7)  (0) 2019.09.24
Simple server & client socket 예제  (0) 2019.09.22
Buffer class의 이해  (0) 2019.09.22
NioSample  (0) 2019.09.22
Posted by easy16
java2019. 9. 22. 22:43

Socket 및 In/Out stream 다루는 부분을 중점적으로 확인

 

Socket과 InputStream, OutputStream을 사용한다는 것을 기억.

 

ex)

public class SocketTest {
	
	
	public SocketTest() {
		super();
		
		new Thread() {
			public void run() {				
				ServerTestSampleRun();
			};
		}.start();
		
		new Thread() {
			public void run() {				
				ClientTestSampleRun();
			};
		}.start();
		
		
	}

	
	private void ServerTestSampleRun() {
		ServerSocket server = null;
		Socket client= null;
		
		
		
		try {
			
			server = new ServerSocket(9999);//server 객체 생성
			
			while(true) {
				
				System.out.println("server : Waiting for request...");
				client = server.accept();//socket 생성 후, client의 연결을 대기
				
				System.out.println("server : accepted");
				
				InputStream stream = client.getInputStream();//client로 부터의 메세지를 받기 위한stream
				BufferedReader  in = new BufferedReader(
						new InputStreamReader(stream));//문자열 처리를 위해 사용
				String data = null;
				StringBuilder receivedData = new StringBuilder();
				
				while((data = in.readLine())!=null){
					receivedData.append(data);
				}
				System.out.println("received data : "+receivedData.toString());
				
				
				in.close();
				stream.close();
				client.close();
				
				if(receivedData!=null && "EXIT".equals(receivedData.toString())) {
					System.out.println("stop SocketServer");
					break;
				}
				
				System.out.println("-------");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if( server != null)
					server.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
	}

	
private void ClientTestSampleRun() {
		
		
		for ( int loop = 0 ; loop < 3 ; loop++) {
			sendSocketData("I hate java at "+ new Date());
		}
		
		sendSocketData("EXIT");
	}

	private void sendSocketData(String data) {
		Socket socket = null;
		try {
			System.out.println("client : connecting...");
			socket = new Socket("127.0.0.1", 9999);//socket을 만드는 것만으로도 연결이 수행
			System.out.println("client : connect status = "+socket.isConnected());
			
			Thread.sleep(1000);
			OutputStream stream = socket.getOutputStream();//server로 데이터 전송을 위한 stream을 가져옴.
			BufferedOutputStream out=
					new BufferedOutputStream(stream);
			byte[] bytes = data.getBytes(); 
			out.write(bytes);
			
			System.out.println("client : send data");
			out.close();
			
			 Thread.sleep(3000);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}

출처 : 자바의 신

Posted by easy16
java2019. 9. 22. 15:36

flip means-> set limit to current position and set position to 0

 

ex)

private void intBufferTest(){
		
	IntBuffer buffer = IntBuffer.allocate(1024);
	for ( int loop  = 0 ; loop < 100 ; loop ++) {
		buffer.put(loop);
	}
	
	
	System.out.println("Buffer capacity : " + buffer.capacity() );
	System.out.println("Buffer limit 	: " + buffer.limit() );
	System.out.println("Buffer position : " + buffer.position() );
	buffer.flip();
	System.out.println("Buffer flipped! set limit to current position! and set position to  " );
	System.out.println("Buffer limit 	 : " + buffer.limit() );
	System.out.println("Buffer position : " + buffer.position() );
	
	
}

출처 : 자바의 신

Posted by easy16
java2019. 9. 22. 15:21

ex)


public class NioSample {
	
	
	public NioSample() {
		super();
		
		basicWriteAndRead();
		
	}
	
	
	private void basicWriteAndRead() {
		String fullPath = "C:"+File.separator+"Users"+File.separator+"Lee"+File.separator+"test"+File.separator+"nio.txt";
		
		try {
			writeFile(fullPath, "Nio sample");
			readFile(fullPath);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			
		}
		
		
	}




	private void writeFile(String fullPath, String data) throws Exception {
		FileChannel channel = new FileOutputStream(fullPath).getChannel();//channel 객체 생성
		byte [] byteData = data.getBytes();
		ByteBuffer buffer = ByteBuffer.wrap(byteData); //ByteBuffer 생성방법 : bytearray를 wrap method에 전달
		channel.write(buffer); // write 함수 호출
		channel.close();		
	}
	
	private void readFile(String fullPath) throws Exception{
		FileChannel channel = new FileInputStream(fullPath).getChannel();//channel 객체 생성
		ByteBuffer buffer = ByteBuffer.allocate(1024);// ByteBuffer 할당
		channel.read(buffer);//read 메소드에 버퍼를 전달
		
		buffer.flip(); //buffer 객체의 맨 앞으로 이동
		//Flips this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded. 
		while(buffer.hasRemaining()) {
			System.out.print((char)buffer.get());// 한 바이트씩 읽음.
		}
		channel.close();
	}
	
	

}

 

출처 : 자바의 신

Posted by easy16
java2019. 9. 22. 15:01

Serializable interface, transient 예약어

FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream 예제

ex)



public class SerialDTO implements Serializable { //Serializable를 반드시 구현해야 ObjectStream class들을 이용가능하다.
	
	private String bookName;
	private int bookOrder;
	//transient private int bookOrder;// transient로 선언된 변수는 저장 되지 않는다 (security) 
	
	
	private String bookType="IT";//추가시  local class incompatible 발생
	static final long serialVersionUID = 1l; //serialVersionUID를 명시적으로 설정하면 class에 변경이 생겨도 같은 객체로 인식하여 로딩이 가능해진다.
	
	public SerialDTO( String bookName , int bookOrder) {
		super();
		this.bookName = bookName;
		this.bookOrder= bookOrder;
	}
	
	@Override
	public String toString() {

		
		//return String.format("bookName : %s bookOrder : %d",bookName,bookOrder);
		return String.format("bookName : %s bookOrder : %d bookType : %d",bookName,bookOrder,bookType);
	}

}


public class ManagerObject {

	
	
	public void runManager() {
		String fullPath = "C:"+File.separator+"Users"+File.separator+"Lee"+File.separator+"test"+File.separator+"Test.obj";
		SerialDTO dto = new SerialDTO("fantasy", 123);
		
		//saveObject(fullPath ,dto);
		loadObject(fullPath);
	}
	private void saveObject( String fullPath, SerialDTO dto) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		
		
		try {
			fos = new FileOutputStream(fullPath);//FileOutputStream(fullPath) 객체를 생성후, ObjectOutputStream 생성자에 전달 
			oos = new ObjectOutputStream(fos);
			oos.writeObject(dto);//쓰기
			System.out.println("write done");
			
			
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if ( fos != null)
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if( oos!= null)
				try {
					oos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		
		
	}

	private void loadObject(String fullPath) {
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = new FileInputStream(fullPath);
			ois = new ObjectInputStream(fis);
			
			
			try {
				SerialDTO dto = (SerialDTO)ois.readObject();
				System.out.println(dto);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if( fis != null)
				try {
					fis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if ( ois != null)
				try {
					ois.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		
		
		
		
	}

	
	
		
		
	
}

출처 : 자바의 신

'java' 카테고리의 다른 글

Buffer class의 이해  (0) 2019.09.22
NioSample  (0) 2019.09.22
FileReader 및 BufferedReader + (Scanner)  (0) 2019.09.22
FileWriter 및 BufferedWriter 텍스트기반 처리  (0) 2019.09.22
FileFilter , FileNameFilter interface  (0) 2019.09.21
Posted by easy16
java2019. 9. 22. 00:14

 

종료시 close는 반드시 호출할 수 있도록 하며, try ~ finally 구문에 넣어주는 것이 좋다.
자세한 내용은 예제를 통해 참조

ex)


public class StreamTest {
	
	
	
	public StreamTest() {
		super();
		this.test();
	}

	private void test() {
		String fullPath = "C:"+File.separator+"Users"+File.separator+"Lee"+File.separator+"test"+File.separator+"numbers.txt";
		//writeFile(fullPath,10);
		readFile(fullPath);
	}

	private void writeFile(String fullPath, int i) {
		FileWriter fileWriter=null;
		BufferedWriter bufferedWriter=null;
		
		try {
			//fileWriter= new FileWriter(fullPath); //write mode.
			fileWriter= new FileWriter(fullPath, true);//append mode
			bufferedWriter = new BufferedWriter(fileWriter);
			
			for ( int loop=0; loop < i ; loop ++) {
				bufferedWriter.write(Integer.toString(loop));
				bufferedWriter.newLine();
			}
		
			System.out.println("Write done!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		} finally {
			
			if( bufferedWriter!=null) {
				try {
					bufferedWriter.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} 
			
			if (fileWriter != null) {
				
				try {
					fileWriter.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
		private void readFile(String fullPath) {
			FileReader fileReader=null;
			BufferedReader bufferedReader=null;
			
			try {
				//
				fileReader= new FileReader(fullPath);
				bufferedReader = new BufferedReader (fileReader);
				
				String data;
				
				while((data = bufferedReader.readLine()) != null ){
					System.out.println(data);
				}
			
				System.out.println("Read done!");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
			} finally {
				
				if( bufferedReader!=null) {
					try {
						bufferedReader.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} 
				
				if (fileReader != null) {
					
					try {
						fileReader.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
			
			
			
		}

		private void readFileWithScanner( String fileName) {
				
			File file = new File(fileName);
			
			Scanner scanner = null;
			
			try {
				scanner = new Scanner(file);
				while (scanner.hasNextLine()) {
					System.out.println(scanner.nextLine());
				}
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				if (scanner != null)
					scanner.close();
			}
			
            
            
            /* 이하 동일, 참조
            		
			try {
				String data = new String(Files.readAllBytes(Paths.get(fileName)));
				System.out.println(data);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();				
			}
            
            */

		}
        
        
        	
}

 

 

출처 : 자바의 신

Posted by easy16