메인은 사실 메인 쓰레드라고 부른다

public static void main(String[] args) {

 

쓰레드 인스턴스 생성

MyThread t0 = new MyThread(10);
MyThread t1 = new MyThread(3);
MyThread t2 = new MyThread(8);
MyThread t3 = new MyThread(100);
MyThread t4 = new MyThread(100);

 

메인 쓰레드는 다른 쓰레드의 시작 버튼만 눌러주고 코드를 계속 진행한다

t0.start();
t1.start();
t2.start();
t3.start();

 

 

Thread.sleep(ms초) : 현재 쓰레드를 (ms)초 멈춘다

 

class AssistThread extends Thread {
	
	int parent;
	
	public AssistThread(int parent) {
		this.parent = parent;
		this.setDaemon(true);
	}
	
	@Override
	public void run() {
		while (true) {
			System.out.printf("%d번 쓰레드의 보조 쓰레드(데몬)입니다...\n", parent);
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

 

Thread 클래스를 상속받으면 main과 동시에 동작할 수 있는 쓰레드가 된다

class MyThread extends Thread {
	
	static int totalNumber = 0;
	
	int num;
	int target;
	
	public MyThread(int target) {
		num = totalNumber++;
		this.target = Math.abs(target);
	}
	
	@Override
	public void run() {
		new AssistThread(num).start();;
		
		// 이 쓰레드의 main같은 곳
		// 메인 쓰레드 또는 다른 쓰레드에서 이 쓰레드를 실행하면 이곳의 코드를 실행한다
		int i = 0;
		while (i++ < target) {
			System.out.printf("Thread%d: %d\n", num, i);
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

'JAVA' 카테고리의 다른 글

Network  (0) 2024.07.08
PrintStream  (0) 2024.07.05
Buffered  (0) 2024.07.04
AutoClose  (0) 2024.07.01
File  (0) 2024.06.29
Scanner sc = new Scanner(System.in);

 

소켓은 인스턴스 생성시 접속할 IP주소와 포트번호가 필요하다
소켓 생성시 서버가 올바르다면 접속이 완료된다

try(
        Socket s = new Socket("192.168.0.1", 9090);
) {
    try (
            PrintStream out = new PrintStream(s.getOutputStream());
            BufferedInputStream in = new BufferedInputStream(s.getInputStream());
    ) {
        System.out.println(new String(in.readAllBytes()));
        while (true) {
        out.println("> ");
        out.println(sc.nextLine());
        }
    }
} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

'JAVA' 카테고리의 다른 글

Thread  (0) 2024.07.08
PrintStream  (0) 2024.07.05
Buffered  (0) 2024.07.04
AutoClose  (0) 2024.07.01
File  (0) 2024.06.29

- 문자를 훨씬 편리하게 출력할 수 있는 메서드들이 추가된 클래스
- println(), printf(), print() 등의 메서드를 사용할 수 있다
- Buffered -> 성능 증가
- Print -> 편리함 증가

 

특징

 

  • 편리한 출력: println(), printf(), print() 등으로 데이터를 편리하게 출력
  • 버퍼링 지원: Buffered 기능을 통해 성능이 증가
  • 편리성 증가: 데이터를 다양한 형식으로 출력할 수 있어 편리
  • 자동 플러시: println(), printf(), print() 메서드 사용 시 자동으로 플러시가 발생하여 출력

 

활용 메서드

 

  • printf(String format, Object... args): 지정한 형식으로 문자열을 출력
  • println(String x): 문자열을 출력한 후 개행을 추가
  • print(String x): 문자열을 출력하지만 개행은 추가

 

 // 파일 객체 생성
File f = new File("myfiles/print.txt");

try (
    // FileOutputStream을 사용해 파일에 출력
    FileOutputStream fout = new FileOutputStream(f, true);
    // PrintStream을 통해 데이터를 출력
    PrintStream out = new PrintStream(fout);
) {
    // 포맷을 사용한 출력
    out.printf("%s: %d\n", "Age", 25);
    // 문자열 출력 및 개행
    out.println("Hello, world!~!");
    // 한글 출력 및 개행
    out.println("한글~!!");
} catch (IOException e) {
    e.printStackTrace();
}

 

 

 

 

'JAVA' 카테고리의 다른 글

Thread  (0) 2024.07.08
Network  (0) 2024.07.08
Buffered  (0) 2024.07.04
AutoClose  (0) 2024.07.01
File  (0) 2024.06.29

- 데이터를 하나씩 전송하는 것이 아니라 모아서 한번에 전송하는 기능을 제공하는 클래스
- 앞에 Buffered가 붙은 클래스를 사용하면 알아서 버퍼 방식이 적용된다
- BufferedReader/Writer : 버퍼 기능 + char 단위 입출력
- BufferedInputStream/OutputStream : 버퍼 기능 + byte 단위 입출력
- InputStreamReader : byte단위의 스트림을 char단위로 업그레이드 해주는 클래스

 

Long start, end;

한 글자씩 출력해주는 버퍼 생성 

File testFile = new File("myfiles/test.txt");
		
long start, end;

 

비교를 하기 위한 시간초 세기

start = System.currentTimeMillis();

 

try (
        FileReader in = new FileReader(testFile);
) {
    int ch;
    while ((ch = in.read()) != -1) {
        System.out.print((char)ch);
    }
} catch (IOException e) {
    e.printStackTrace();
}

 

end - start 로 걸린 시간 측정

end = System.currentTimeMillis();
long time1 = end - start;
System.out.println("걸린시간1: " + time1 + "ms");

 

 

 

똑같이 시간을 재는 Long 타입 time2 선언

long time2 = end - start;

start = System.currentTimeMillis();
try (
        FileReader fin = new FileReader(testFile);
        BufferedReader in = new BufferedReader(fin);
) {

 

Buffered 스트림에는 한 줄씩 읽는 기능이 추가되어 있다
읽을것이 있으면 읽을 내용을 반환, 없으면 null을 반환

String line;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}
end = System.currentTimeMillis();

 

System.out.println("걸린시간2: " + time2 + "ms");

 

한줄씩 읽을 경우 0ms

 

Scanner 대신 Buffered 클래스를 사용하여 콘솔로부터 입력받기
(Scanner는 들어오는 문자에 대한 정규표현식 검사를 하기 때문에 속도가 훨씬 느리다)

try (
    InputStreamReader in = new InputStreamReader(System.in);
    BufferedReader sc = new BufferedReader(in);
) {
    while (true) {
        if (sc.readLine().equals("exit")) {
            break;
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println("걸린시간3: " + time3 + "ms");

 

'JAVA' 카테고리의 다른 글

Network  (0) 2024.07.08
PrintStream  (0) 2024.07.05
AutoClose  (0) 2024.07.01
File  (0) 2024.06.29
JavaIO  (0) 2024.06.15

닫을 수 있는(Closeable 인터페이스가 구현된) 클래스는
try문을 사용할 때 AutoClose 문법을 사용할 수 있다

try문에 ()을 열고 사용한 변수는 try문이 끝나면서 자동으로 닫히게 된다

 

try (
    FileReader in = new FileReader("myimages/memo/test.txt");
    FileWriter out = new FileWriter("myimages/memo/test.txt", true);
) {

 

FileWriter의 append값을 true로 주면 추가 모드가 되어서
파일에 내용을 계속 누적시키게 된다

 

			out.write("안녕하세요~\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

'JAVA' 카테고리의 다른 글

PrintStream  (0) 2024.07.05
Buffered  (0) 2024.07.04
File  (0) 2024.06.29
JavaIO  (0) 2024.06.15
Exception  (0) 2024.06.12

# java.io.file


  
   - 파일에 대한 정보를 담을 수 있는 클래스
   - 있는 파일의 정보를 담을 수도 있고 
     아직 존재하지 않는 파일의 정보를 만들어 놓고 새 파일을 생성할 수도 있다

 

파일 생성

File f1 = new File("myfiles/test.txt");
File f2 = new File("myfiles/notexist.txt");
File f3 = new File("myfiles/image.txt");
File f4 = new File("myfiles");

 

exists() : 해당파일이 존재하는지 알 수 있다

System.out.println(f1.exists());
System.out.println(f2.exists());
System.out.println(f3.exists());
System.out.println(f4.exists());

 

 

canRead(), canWrite(), canExecute()

    읽기              쓰기                실행

해당 파일의 권한을 확인 할 수 있다

System.out.println(f1.canRead());
System.out.println(f1.canWrite());
System.out.println(f1.canExecute());

 

 getAbsolutePath() 해당 파일의 절대 경로를 알아낼 수 있다

System.out.println(f1.getAbsolutePath());

 

isFile(), isDirectory() : 해당 인스턴스가 파일인지 폴더인지 알아낼 수 있다

System.out.println(f1.isFile());
System.out.println(f2.isFile());
System.out.println(f3.isFile());
System.out.println(f4.isFile());

System.out.println(f1.isDirectory());
System.out.println(f2.isDirectory());
System.out.println(f3.isDirectory());
System.out.println(f4.isDirectory());

 

절대 경로 : 최초의 위치부터 모든 것을 다 적어놓은 경로
상대 경로 : 현재 위치에서부터 원하는 파일을 찾아가는 경로 
   (나의 현재 위치에 따라 결과가 달라질 수 있다)
  
   ./  : 현재 위치 (생략 가능)
   ../ : 현재 위치의 상위 폴더
  
   C:/java/workspace/src - 절대경로
   (C/D 같이 드라이브에서 시작하는 경로가 아니면 상대경로)
   myfiles/email.txt - 상대경로

 

ff1 절대경로파일 생성

ff2 상대경로파일 생성

File ff1 = new File("C:/aiautomation_jhd/"
        + "java-workspace/JavaStudy/myfiles/email.txt");
File ff2 = new File("./myfiles/email.txt");

 

isAbsolute() : 절대경로인지 여부를 확인

System.out.println(ff1.isAbsolute());
System.out.println(ff2.isAbsolute());

 

File ff3 = new File("./myimages");
File ff4 = new File("./mymusic/rock/");

 

mkdir() : 해당 경로에 디렉토리(폴더)를 생성

 부모 폴더가 없으면 생성하지 않는다

if (!ff3.exists()) {
    ff3.mkdir(); 
}

 

mkdirs() : 해당 파일을 만들기 위한 부모 폴더까지 모두 만들어버린다 

if (!ff4.exists()) {
    ff4.mkdirs();
}

 

파일생성

File fff1 = new File("myfiles");
File fff2 = new File("myfiles/email.txt");

 

list() : 해당 경로(폴더) 내부에 존재하는 모든 파일들을 볼 수 있다

String[] fileNames = fff1.list();
		
		
for (String fileName : fileNames) {
    // 하나씩 꺼낸 파일 이름으로 또 파일 객체를 생성
    File childFile = new File(fff1, fileName);

    System.out.println(childFile.getAbsolutePath());
}
System.out.println("파일의 리스트를 보는 경우: " + fff2.list());

 

listFiles() : 폴더 안에 내용을 File[]로 꺼내준다

File[] files = fff1.listFiles();

for (File file : files) {
    System.out.println(file);
}

 

 FileReader, FileWriter, FileInputStream, FileOutputStream 

   파일을 다루는 스트림 클래스들은 파일 객체를 사용할 수 있다

try {
    FileReader in = new FileReader(new File("myfiles/email.txt"));

    int ch = in.read();
    while ((ch = in.read()) != -1) {
        System.out.print((char)ch);
    }
    in.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

'JAVA' 카테고리의 다른 글

Buffered  (0) 2024.07.04
AutoClose  (0) 2024.07.01
JavaIO  (0) 2024.06.15
Exception  (0) 2024.06.12
Calendar  (0) 2024.06.11

   # IO (Input/Output)
  

   - 데이터의 입력과 출력을 의미한다
   - 자바는 스트림이라는 개념을 통해 프로그램의 입/출력을 다룬다
   - 프로그램으로 데이터가 들어오는 것을 입력(Input)이라고 한다
   - 프로그램에서 계산되어 나가는 모든 데이터들을 출력(Output)이라고 한다
  

   # Stream
  

   - 데이터들이 오고 가는 통로
   - 데이터들이 프로그램으로 들어오는 통로를 InputStream이라고 한다
   - 데이터들이 프로그램에서 나가는 통로를 OutputStream이라고 한다
   - 데이터가 Stream을 지나가기 위해서는 해당 데이터를 byte타입으로 변환해야 한다
     (byte 타입이 0과 1로 변환하기 가장 쉬운 형태이기 때문에) 

 

 파일로 데이터를 내보낼 수 있는 통로를 생성한다
 (저장매체(CD, USB, HDD, SSD 등)로 데이터를 내보낼 수 있는 통로를 생성한다)

myfiles/a-test,txt 생성

 

try {
    FileOutputStream out = new FileOutputStream("myfiles/a-test.txt");

 

OutputStream으로는 byte범위를 벗어나는 값을 다룰 수 없다

 

try {
    out.write('한');
    out.write(66);
    out.write(67);
    out.write('\n');

 

 

"".getByte() : 해당 인스턴스를 byte[]로 변환하여 반환한다

out.write("Hello, world!\n".getBytes());
out.write("안녕하세요~".getBytes());

 

다 사용한 통로는 반드시 닫아줘야 한다 (안닫아주면 메모리 누수 발생)

※ 메모리 누수 : 프로그램이 오랫동안 켜져있는 경우 차지하는 메모리 용량이 
              점점 커지는 현상(운영체제에 의해 강제종료 됨)

out.close();

 

마무리로 전부 닫아준다

} catch (IOException e) {
        e.printStackTrace(); // 통로로 입력하던 도중 발생한 예외
    }

} catch (FileNotFoundException e) {
    e.printStackTrace(); // 파일 통로 생성 도중 발생한 예외
}

 

 

'JAVA' 카테고리의 다른 글

AutoClose  (0) 2024.07.01
File  (0) 2024.06.29
Exception  (0) 2024.06.12
Calendar  (0) 2024.06.11
Date  (0) 2024.06.07

   예외 (Exception)
  
   - 우리가 에러라고 생각했던 빨간 글씨들을 예외라고 부른다
   - 프로그래머는 발생할 수 있는 예외를 미리 예상하고 대비해둘 수 있다 (예외 처리)
   - 자바의 문법을 틀리는 것은 예외가 아니라 컴파일 에러라고 부른다
  
    예외 처리 (try-catch문)
  
   - 예외가 발생할 수도 있는 코드를 try문 내부에 포함시킨다
   - try문 내부에서 예외가 발생하지 않으면 정상적으로 작동한다
   - try문 내부에서 예외가 발생하는 경우 발생한 예외에 대한 catch문으로 이동한다
   - 예외가 발생했을때 예외처리가 되어있지 않은경우 프로그램이 강제종료되지만
     해당 예외에 대한 처리가 되어있는 경우 프로그램이 강제종료되지 않는다
   - 예외가 발생하여 해당 catch문에 도착할 때 발생한 예외에 대한 정보를 담고있는
     인스턴스가 함께 도착한다
   - 예외 처리를 하지 않았을 때의 기본 동작은 e.printStackTrace()후 강제 종료이다
  
    finally
  
   - try문 내부에서 예외가 발생하던 안하던 무조건 실행하게 되는 문법

 

try {
   int size = 10 / 1; // 발생 가능한 예외 1
   int[] arr = new int[size];
   System.out.println(arr[-1]); // 발생 가능한 예외 2
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
   System.out.println("인덱스가 잘못된 숫자입니다");
} catch (java.lang.ArithmeticException e) {
   e.printStackTrace();
   System.exit(-1);
}

 

스택(프로그램에서 함수 호출 순서를 기억하기 위한 자료구조)
main() -> plus() -> plus2() -> plus3()
plus3() -> plus2() -> plus() -> main()

 

try {
    System.out.println(plus(10));
} catch(ArithmeticException e) {
    e.printStackTrace();
}

try {
    int[] nums = new int[3];
    nums[(int)(Math.random() * 5)] = 7;


} catch (Exception e) {
    // Exception은 모든 예외객체의 조상 클래스이기 떄문에
    // 모든 예외가 이 catch문으로 도착할 수 있다
    System.out.println("예외가 발생했습니다!");
} finally {
    // try문 내부에서의 예외 발생 여부와 관계없이 무조건 실행하고 싶은 코드를 
    // finally에 적는다
    System.out.println(" /)/)");
    System.out.println("(  ..)");
    System.out.println("(  >$");
}

System.out.println("프로그램이 정상 종료되었습니다");

 

public static int plus(int a) {
    return plus2(a + 10);
}

public static int plus2(int a) {
    return plus3(a);
}

public static int plus3(int a) {
    return a / 10;
}

 

 

'JAVA' 카테고리의 다른 글

File  (0) 2024.06.29
JavaIO  (0) 2024.06.15
Calendar  (0) 2024.06.11
Date  (0) 2024.06.07
정규표현식 (Regex)  (0) 2024.06.07

+ Recent posts