728x90


StringTokenizer

Method

  public String nextToken() : 파싱된 문자열을 차례대로 넘겨준다
  public boolean hasMoreTokens() : 파싱된 문자열이 nextToken()메서드를 실행한 후  문자열 토큰이 남아있는가?
                                                    있으면 true 리턴
  public int countTokens() : 파싱된 문자열 갯수를 리턴 

import java.util.*;

class StringTokenizerTest
{
 public static void main( String [] args )
 {
  StringTokenizer st = new StringTokenizer(" 졸려 | 자고싶어 | 별로 없어요 | 생각안남 | 로또 1등 되고 싶어요","|");
  System.out.println("파싱된 문자열 갯수 :" +st.countTokens() + "개 \n");
  // | 이 분리기호  분리기호를 안쓰면 공백이 분리기호가 된다.
  
  while(st.hasMoreTokens())
  {
   System.out.println(st.nextToken());
  }
  
  StringTokenizer st3 = new StringTokenizer("막걸리도 마시면 취하리");
  while(st3.hasMoreTokens())
  {
   System.out.println(st3.nextToken());
  }
  
 }// end main

}

import java.util.*;
class StringTokenizerTest_2
{
 public static void main( String [] args )
 {
  String str = "서울시:마포구  서울시:강남구 서울시:성북구";
  String temp[] = str.split(" ");
  StringTokenizer st = null;
  for(int i = 0; i < temp.length; i++)
  {
   st = new StringTokenizer(temp[i],":");
   while(st.hasMoreTokens())
   {
    System.out.println(st.nextToken());
   }
   System.out.println();
  }
 }// end main
}
 

728x90

 

StringBuffer클래스 : 문자열을 동적으로 처리
생성자
StringBuffer() : 디폴트 생성자
StringBuffer(int size) :  size를 기본크기로 지정
StringBuffer(String str) : str 초기문자열 지정

메서드
StringBuffer append(booleab b) : 현재 문자열 끝에 b를 추가
StringBuffer append(char ch) : 현재문자열 끝에 ch를 추가
StringBuffer append(int i) : 현재 문자열 끝에 i 를 추가
StringBuffer append(long l) : 현재문자열 끝에 l 를 추가
StringBuffer append(float f) :현재문자열 끝에 f 를 추가
StringBuffer append(double d) :현재문자열 끝에 d 를 추가
StringBuffer append(String str) :현재문자열 끝에 str문자열을 추가
StringBuffer append(Object obj) : 현재문자열 끝에 obj 를 추가

int capacity() : 현재 문자열의 버퍼크기를 반환

char charAt(int index) :  index 위치에 해당 문자열을 반환

StringBuffer insert(int i ,boolean b) : i번 인덱스 앞에 b를 추가
StringBuffer insert(int i,char ch); i번 인덱스 앞에 ch 를 추가
StringBuffer insert(int i, int j) : i번 인덱스 앞에 j를 추가
StringBuffer insert(int i, long l) :i번 인덱스 앞에 l 를 추가
StringBuffer insert(int i, String str) :i번 인덱스 앞에 str 문자열을 추가
StringBuffer insert(int i,Object obj) : i번 인덱스 앞에 obj를 추가

int length() : 문자의 개수를 반환

StringBuffer reverse() : 문자열을 역순으로 변환해 준다
void setCharAt(int i, char ch) : i번째 문자를 ch로 바꾼다
void setLength(int len) : 버퍼크기를 len 크기로 재설정 


class StringBufferTest
{
 public static void main( String [] args )
 {
  StringBuffer sb1 = new StringBuffer("Java");
  StringBuffer sb2 = new StringBuffer(10); // capacity를 10 으로
  StringBuffer sb3 = new StringBuffer();// default 생성자
  // capacity는 기본이 16으로 잡힌다.
  
  
  System.out.println(sb1.length());
  System.out.println(sb1.capacity());
  System.out.println();
  System.out.println(sb2.length());
  System.out.println(sb2.capacity());
  System.out.println();
  System.out.println(sb3.length());
  System.out.println(sb3.capacity());
 }// end main

}



class StringBufferTest_2
{
 public static void main( String [] args )
 {
  StringBuffer sb = new StringBuffer();
  sb.append("Hello ");
  sb.append("Good ");
  System.out.println("스트링 버퍼 클래스 값 :"+ sb.toString());
  
  sb.reverse();
  System.out.println(sb.toString());
  
  sb.reverse();
  sb.delete(0,5);
  System.out.println(sb.toString());
  
  System.out.println(sb.length());
  System.out.println(sb.capacity());
  
  sb.append("very ");
  sb.append("nice ");
  sb.append("Oh my god ");
  sb.append("see you tomorrow");
  System.out.println(sb.capacity());
 }// end main
}


class StringBufferTest_3
{
 public static void main( String [] args )
 {
  StringBuffer sb  = new StringBuffer("java");
  sb.append(" program");
  
  for(int i = 0 ; i<sb.length(); i++)
  {
   System.out.print("\n"+sb.charAt(i));
  }
  
  sb.insert(4,"★"); //입력위치에 값이 있으면 뒤로 밀어내고 입력.
  System.out.println("\n"+sb);
  
  System.out.println(sb.length());
  sb.setLength(5);                     //문자열 길이 다시 설정
  System.out.println(sb.length());
  System.out.println(sb.toString());
 }// end main
}

/*
String 과 StringBuffer 연산 시간 차이 구하는 예제
 */

class StringBufferTest_4
{
 public static void main( String [] args )
 {
  long start, end;
  String str1 = new String("1 ~ 5000까지 합을 연산하기 ");
  start = System.currentTimeMillis(); // 시작시간 구하기
  for(int i = 1; i<=5000 ; i++)
  {
   str1+=i;
   str1+="+";
  }
  end = System.currentTimeMillis(); //연산 종료 시간
  System.out.println("연산시간: " + (end - start));
  
  
  StringBuffer sb = new StringBuffer("1~5000까지 연산 시간");
  start = System.currentTimeMillis();
  
  
  for(int i = 1; i<=5000; i++)
  {
   sb.append(i);
   sb.append("+");
   
  }
  end = System.currentTimeMillis(); //연산 종료 시간
  System.out.println("StringBuffer 연산시간: " + (end - start));
  
 }// end main
}

728x90

 기본자료형
 byte
 boolean
 char
 short
 int
 long
 float
 double
 WrapperClass
 Byte
 Boolean
 Character
 Short
 Integer
 Long
 Float
 Double

자료형을 효율적으로 관리함과 동시에 완벽한 은닉화를 추구하기 위해 만들어진 자료형 대체 클래스

class WrapperClassTest
{
 public static void main(String args[])
 {
  boolean b = true;
  Boolean B = new Boolean(b);
  
  int i = 30;
  Integer I = new Integer(i);
  
  float f = 23.5f;
  Float F = new Float(f);
  
  System.out.println("Wrapper 클래스 값 :" +B.toString());
  System.out.println("Wrapper 클래스 값 :" +I.toString());
  System.out.println("Wrapper 클래스 값 :" +F.toString());
  
  int v = 100;
  //String str = (String)v; //에러
  //String str = v+"";
  String str = Integer.toString(v);
  System.out.println(str);
 }
}

 

728x90

IO


 자바의 스트림은 문자 스트림과 바이트 스트림으로 구분할 수 있다.
 문자스트림은 16비트단위로, 바이트 스트림은 8비트 단위로 데이터를 읽고,쓴다.
 문자스트림은 메모장으로 읽을 수 있고, 바이트 스트림은 메모장으로 읽지 못한다.
 문자스트림은 16비트 유니코드로 데이터를 입출력할 때 사용합니다.

  - Writer추상클래스는 모든 문자 출력 스트림에 사용할 수 있는 기능을 정의하고 있다.
  - OutputStreamWriter클래스는 특정 문자 인코딩 규칙에 따라 문자 스트림을 바이트 스트림으로 변환한다.
  - FileWriter클래스는 OutputStreamWriter를 확장(상속)하고 문자를 파일에 출력합니다.
  
   - 생성자
       OutputStreamWriter(OutputStream os) throws IOException
        =>특정문자 인코딩 규칙에 따라 문자스트림을 바이트 스트림으로 변환한다.
       OutputStreamWriter(OutputStream os, String encording) throws IOException
        => os는 출력스트림이고 encording은 문자 인코딩 이름이다.
  
       FileWriter(String filepath) throws IOException
        => filepath(파일경로)
       FileWriter(String filepath, boolean addend) throws IOException
        => append가 true 이면 문자 파일 끝에 추가한다.
       FileWriter(File fileObj)
        =>fileObj는 그 파일을 나타내는 파일의 객체이다.

       InputStreamReader(InputStream is) throws IOException
        => is는 입력스트림, encoding은 사용자 시스템에 설정된 기본문자 인코딩 적용      
       InputStreamReader(InputStreamis, String encoding) throws IOException

        => encoding은 문자 인코딩 이름

       FileReader(String filepath)
        => filepath 파일 전체 경로 이름
       FileReader(File fileObj)
        => 그 파일을 나타내는 File객체이다.

     -메소드

       void close() => 입출력 스트림 닫기
       void flush() => 출력 스트림 내용을 비운다.
       void write(int c) => 한 문자 쓰기  // int형 하위 2바이트
       void write(char buffer[], int index, int size) => index위치부터 size만큼 스트림에  출력한다.
       void write(String s) => 문자열 쓰기
       void write(String s, int index, int size) =>index위치부터 size만큼 문자열 쓰기
       int read() => 한 문자를 읽는다.
       int read(char buffer[]) => 입력스트림에서 buffer배열로 문자를 읽어온다. 
       int read(char buffer[], int offset, int num) => 입력스트림에서 num 만큼 문자를 읽어 읽은 문자 개수 리턴

문자스트림 클래스 내부

 Objcet  -  Reader  -   BufferedReader
                                InputStreamReader   -  FileReader
               Writer     -   BufferedWriter
                                OutputStreamWriter   -  FileWriter
                                PrintWriter

바이트스트림 클래스 내부

  Object  -  ImputStream  -  FileInputStream
                                        FilerInputStream    -   BufferedInputStream
                                                                       DataInputStream
             - OutputStream  -  FileOutputStream
                                        FilterOutputStream  -  BufferedOutputStream
                                                                       DataOutputStream
                                                                       PrintStream

FileWrite
public FileWriter(String fileName) throws IOException
  Constructs a FileWriter object given a file name.


import java.io.*;
class FileW
{
 public static void main(String args[])throws IOException
 {
  
  FileWriter fw = null;
  try
  {
   fw = new FileWriter("a1.txt");// 객체생성
   for(int i = 1; i<=5 ; i++)
   {
    fw.write("줄번호:" +i+"\n");//파일에 문자열 쓰기
   }
   fw.close();
  }
  catch(Exception e)
  {
   System.out.println("예외:" +e);
  }
  finally
  {
   try
   {
    if(fw != null)
    {
     fw.close();
    }
   }
   catch(IOException ioe)
   {
   }
   
  }
 }
}


FileReader
public FileReader(String fileName) throws FileNotFoundException
   Creates a new FileReader, given the name of the file to read from.



import java.io.*;

class FileR
{
 public static void main(String args[]) throws IOException
 {
  FileReader fr = new FileReader("a1.txt");
  int a;
  while((a =fr.read()) != -1)  //파일 끝이 아닌 동안 반복
  {
   System.out.println((char)a);
  }
  fr.close();
 }
}

 

BufferedWriter ( txt 파일에 데이터 쓰기)
Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.


import java.io.*;
class BuffW
{
 public static void main(String args[]) throws IOException
 {
  try
  {
   //FileWriter fw = new FileWriter("b1.txt"); //파일쓰기 객체 생성
   //BufferedWriter bw = new BufferedWriter(fw);
     BufferedWriter bw = new BufferedWriter(new FileWriter("b1.txt"));
   
   //파일에 문자열 쓰기
   for(int i=1 ; i<=7; i++)
   {
    bw.write("줄번호: " +i+ "\n");
   }
   bw.close();
  }
  catch(Exception e)
  {
  }
  finally
  {
  }
 }
}

BufferedReader ( txt 에서 데이터 읽어오기)
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. 


import java.io.*;

class BuffR
{
 public static void main(String args[])
 {
  try
  {
   //FileReader fr = new FileReader("b1.txt"); //파일 읽기 객체 생성
   //BufferedReader br = new BufferedReader(fr); //버퍼 읽기 객체 생성
   BufferedReader br = new BufferedReader(new FileReader("b1.txt"));
   String str;
   
   while((str = br.readLine()) != null)// 파일 끝이 아닌 동안.
   {
    System.out.println(str);
   }
   br.close();
  }
  catch(Exception e)
  {
  }
  finally
  {
  }
 }
}


버퍼와 문자 스트림을 사용하여 키보드로부터 입력을 읽는 예제

System.in 은 InputStream 객체이기 때문에 InputStreamReader의 생성자의 인수로 전달된다.
그런 다음 InputStreamReader 객체가 BufferedReader 생성자 인수로 전달된다.


import java.io.*;
class ReadConsole
{
 public static void main( String [] args ) throws IOException
 {
  try
  {
   //InputStreamReader isr = new InputStreamReader(System.in); //입력스트림 읽기 객체 생성
   //BufferedReader br = new BufferedReader(isr);// 버퍼 읽기 객체 생성
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   String strKor, strEng;
   int kor,eng,tot;
   
   System.out.print("국어점수 입력: ");
   strKor = br.readLine();
   
   System.out.print("영어점수 입력: ");
   strEng = br.readLine();
   
   kor = Integer.parseInt(strKor);
   eng = Integer.parseInt(strEng);
   tot = kor + eng;
   
   System.out.println("총점 :"+ tot);
   
   br.close();
  }
  catch(Exception e)
  {
  }
  finally
  {
  }
 }// end main
}
PrintWriter
public PrintWriter(OutputStream out)
Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.
This convenience constructor creates the necessary intermediate OutputStreamWriter, which will convert characters into bytes using the default character encoding.

/*
자바의 PrintWriter객체는 Object를 비롯한 모든 형식에 대해서 Print()와 Println()를 지원한다
 */

import java.io.*;

class PrintWriterEx
{
 public static void main( String [] args )
 {
  try
  {
   PrintWriter pw = new PrintWriter(System.out);//객체생성
   pw.println(true);
   pw.println('A');
   pw.println(100);
   pw.println(12.4);
   pw.println("호호호");
   pw.close();
  }
  catch(Exception e)
  {
  }
  finally
  {
  }
 }// end main
}


FileOutputStream
public FileOutputStream(String name) throws FileNotFoundException
Creates an output file stream to write to the file with the specified name. A new FileDescriptor object is created to represent this file connection.


import java.io.*;

class ByteW
{
 public static void main( String [] args ) throws IOException
 {
  try
  {
   FileOutputStream fos = new FileOutputStream("c1.txt");
   
   for(int i = 1 ;i<=10; i++)
   {
    fos.write(i);
   }
   fos.close();
  }
  catch(Exception e)
  {
  }
  finally
  {
  }
 }// end main
}


FileInputStream
public FileInputStream(String name)throws FileNotFoundException
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system. A new FileDescriptor object is created to represent this file connection.


import java.io.*;

class ByteR
{
 public static void main( String [] args )
 {
  try
  {
   FileInputStream fis = new FileInputStream("c1.txt"); //입력스트림 객체 생성
   // 데이터를 읽어와 출력하기
   int i;
   
   while ((i = fis.read()) != -1) // 파일 끝이 아닌 동안
   {
    System.out.println(i + " ");
   }
   fis.close();
  
   
  }
  catch(Exception e)
  {
  }
  finally
  {
  }
 }// end main
}

BufferedOutputStream
The class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.


import java.io.*;

class ByteBuffW
{
 public static void main(String args[])
 {
  try
  {
   //FileOutputStream fos = new FileOutputStream("d1.txt"); //파일 출력 스트림 객체 생성
   //BufferedOutputStream bos = new BufferedOutputStream(fos);  // 버퍼 출력 스트림 객제 생성
   BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d1.txt"));
   
   for(int i = 1 ; i<=20; i++)
   {
    bos.write(i);
   }
   bos.close();
  }
  catch(Exception e)
  {
  }
  finally
  {
  }
 }
}


 BufferedInputStream
public BufferedInputStream(InputStream in)
Creates a BufferedInputStream and saves its argument, the input stream in, for later use. An internal buffer array is created and stored in buf.


import java.io.*;

class ByteBuffR
{
 public static void main( String [] args ) throws IOException
 {
  //FileInputStream fis = new FileInputStream("d1.txt");  //파일입력스트림 객체 생성
  //BufferedInputStream bis = new BufferedInputStream(fis);//버퍼 입력 스트림 객체 생성
  BufferedInputStream bis = new BufferedInputStream(new FileInputStream("d1.txt"));
  
  int i;
  
  while((i = bis.read()) != -1)
  {
   System.out.print(i+ " ");
  }
  bis.close();
 }// end main
}


DataOutputStream
A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.
DataIntputStream
A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.


import java.io.*;
class DataOutputStreamEx
{
 public static void main( String [] args ) throws IOException
 {
  try
  {
   //데이터 저장
   DataOutputStream dos = new DataOutputStream(new FileOutputStream("e1.txt"));
   dos.writeBoolean(true);  //자료형 크기대로 읽는다.
   dos.writeChar('A');
   dos.writeByte(Byte.MAX_VALUE);
   dos.writeInt(100);
   dos.writeDouble(100.7);
   dos.writeChars("kim\n");//\n 삽입해야 홍길동이 제대로 나온다.
   dos.writeUTF("홍길동");
   dos.close();
   
   //데이터 읽기
   DataInputStream dis = new DataInputStream(new FileInputStream("e1.txt"));
   System.out.println(dis.readBoolean());
   System.out.println(dis.readChar());
   System.out.println(dis.readByte());
   System.out.println(dis.readInt());
   System.out.println(dis.readDouble());
   System.out.println(dis.readLine());
   System.out.println(dis.readUTF()); //한글사용가능
  }
  catch(Exception e)
  {
  }
  finally
  {
  }
 }// end main
}

 
 

+ Recent posts