문제
텍스트 파일의 이름을 main 함수의 argument로 받아서 파일의 내용을 요약해서 출력.
터미널에서 java FileDetails Yesterday.txt 하면 txt파일을 넘겨주면서 실행한다.
Text file
/* Yesterday.txt */
Yesterday
Yesterday, All my trouble seemed so far away
Now it looks as though they're here to stay
Oh, I believe in yesterday
Suddenly, I'm not half the man I used to be
There's a shadow hanging over me
Oh, yesterday came suddenly
Why she had to go, I don't know she wouldn't say
I said something wrong, now I long for yesterday
Yesterday, Love was such an easy game to play
Now I need a place to hide away
Oh, I believe in yesterday
Why she had to go, I don't know she wouldn't say
I said something wrong, now I long for yesterday
Yesterday, Love was such an easy game to play
Now I need a place to hide away
Oh, I believe in yesterday
(1) Text file의 내용을 출력
/* Yestereday.txt 파일의 내용을 출력해서 보여줌 */
import java.io.FileInputStream;
import java.io.File;
public class test {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java FileDetails FileName");
return;
}
String fileName = args[0];
File file = new File(fileName);
try (FileInputStream stream = new FileInputStream(file)) {
char[] contents = new char[(int)file.length()];
for (int i = 0; i < contents.length; i++) {
contents[i] = (char)stream.read();
}
for (char c: contents) {
if (c == '\n') {
System.out.print("\n");
}
else {
System.out.print(c);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
(1) 실행 결과
Yesterday
Yesterday, All my trouble seemed so far away
Now it looks as though they're here to stay
Oh, I believe in yesterday
Suddenly, I'm not half the man I used to be
There's a shadow hanging over me
Oh, yesterday came suddenly
Why she had to go, I don't know she wouldn't say
I said something wrong, now I long for yesterday
Yesterday, Love was such an easy game to play
Now I need a place to hide away
Oh, I believe in yesterday
Why she had to go, I don't know she wouldn't say
I said something wrong, now I long for yesterday
Yesterday, Love was such an easy game to play
Now I need a place to hide away
Oh, I believe in yesterday
(2) Yesterday.txt의 상세 정보 출력
/* 입력받은 txt 파일의 상세 정보를 출력 */
import java.io.*;
public class FileDetails {
public static void summerize(char[] contents) {
// vowel: 모음, Consonant: 자음
int vowel=0, consonats=0, lines=0;
for (char c : contents) {
if (Character.isLetter(c)) { // Chracter.isLetter -> 글자면 true를 return한다. 아니면 false
if ("AEIOUaeiou".indexOf(c) != -1) { // indexOf(char)는 argument로 char을 넣으면 해당 char에 대한 index를 return한다. 그래서 "0 ~ 배열의 크기" 까지 값이 나올 수 있다.
vowel++;
}
else { // 위의 if가 아니라는 말은 자음이니까
consonats++;
}
}
else if (c == '\n') { // '\n'을 만나면 -> 줄바꿈하라는 뜻이니까 1줄이 끝났다는것. 그래서 lines++함.
lines++;
}
}
System.out.println("Total character count:" + contents.length);
System.out.println("Vowel count: " + vowel); // 모음 수
System.out.println("Consonats count: " + consonats); // 자음 수
System.out.println("Line count: " + lines); // 줄 수
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java FileDetails <file name>");
return;
}
String fileName = args[0]; // fileName에 Yesterday.txt가 저장된다.
// read the file that passed from parameter of main method.
File file = new File(fileName); // java.io.File 클래스를 사용한다, File 클래스의 객체 file을 생성하고 argument로 fileName을 넘겨준다. 이게 경로가 된다. Yesterday.txt 가 경로가됨
// try에 이렇게 () 있으면 try with resource 다.
// try with resource : try절을 나가면 filestream을 무조건 닫아준다. 즉, 오류가 발생하면 무조건 닫아준다는것.
try (FileInputStream stream = new FileInputStream(file)) {
char[] contents = new char[(int)file.length()];
for (int i=0; i<contents.length; i++) {
contents[i] = (char)stream.read(); // .read() 하면 int를 반환하기 때문에 형변환 해줘야함.
}
// for(char c : contents) {
// System.out.print(c);
summerize(contents);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
실행 결과
/* 터미널에 입력 */
> javac FileDetails.java
> java FileDetails Yesterday.java
Total character count:658
Vowel count: 192
Consonats count: 299
Line count: 19
2024.08.25 - [Java] - [Java] 06. 배열
[Java] 06. 배열
Chapter 1: 배열 개요Java에서 배열 표기법배열의 차원배열 요소에 접근배열의 경계 검사배열과 컬렉션 비교 Chapter 2: 배열 생성배열 인스턴스 생성배열 요소 초기화다차원 배열 요소 초기화가변
lightningtech.tistory.com
출처: https://github.com/gikpreet/class-programming_with_java/tree/master
GitHub - gikpreet/class-programming_with_java
Contribute to gikpreet/class-programming_with_java development by creating an account on GitHub.
github.com
'Java > Java 연습 문제' 카테고리의 다른 글
[Java 연습 문제] String Sort (with Bubble Sort) (0) | 2024.09.01 |
---|---|
[Java 연습 문제] 상속을 사용하여 인터페이스 구현 (0) | 2024.08.31 |
[Java 연습 문제] 텍스트 파일의 소문자 복사본 생성 (0) | 2024.08.30 |
[Java 연습 문제] 분수 계산(덧셈, 뺄셈, 곱셈) 코드 (0) | 2024.08.27 |
[Java 연습 문제] 은행 계좌 문제 (0) | 2024.08.27 |