※ Python은 데이터 타입 변환시 int(a)와 같이 입력하지만 Java는 반대로 (int)a로 입력
// console에서 데이터 입력받아 텍스트 파일로 저장
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.io.*;
public class FileWriterEx {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in); // 콘솔을 통하여 입력 가능하게
FileWriter fout = null;
try
{
fout = new FileWriter("C:\\test\\news.txt"); // news.txt를 새로 생성하여 여기에 쓰기 작업
while(true)
{
String line = scanner.nextLine();
if(line.length() == 0) // 엔터키 두 번하면 종료
break;
fout.write(line, 0, line.length()); // 텍스트의 처음(0)부터 마지막(.length)까지를 읽어내 파일에 작성
fout.write("\r\n",0,2); // 마지막에 한줄 띄기위해
}
fout.close(); // writer 종료
} catch (IOException e)
{
System.out.println("입출력 오류");
}
scanner.close();
}
}
// 텍스트 파일 내용 읽어오기
import java.io.*;
public class FileReaderEx
{
public static void main(String[] args)
{
FileReader fin = null;
try
{
fin = new FileReader("C:\\test\\news.txt");
int c;
while ((c = fin.read()) != -1) // 데이터 읽기(문장의 끝에 도달하면 c는 -1을 리턴)
{
System.out.print((char)c); // 읽어온 데이터를 문자로 변환하여 출력
}
fin.close(); // Reader 종료
}
catch (IOException e)
{
System.out.print("입출력 오류");
}
}
}
// FileOutputStream를 이용하여 바이너리 데이터 저장
import java.io.*;
public class FileOutputStreamEx
{
public static void main(String[] args)
{
byte b[] = {7,51,3,4,-1,24};
try
{
FileOutputStream fout = new FileOutputStream("C:\\test\\news.txt"); // 데이터를 저장할 파일 경로 지정
for(int i=0; i<b.length; i++)
fout.write(b[i]); // 바이너리 데이터 파일에 작성
fout.close(); // FileOutputStream 종료
}
catch (IOException e)
{
System.out.println( "C:\\test\\news.txt에 저장할 수 없습니다. 경로명을 확인해 주세요");
return;
}
System.out.println("C:\\test\\news.txt을 저장하였습니다.");
}
}
// 바이너리 데이터 읽기
import java.io.*;
public class FileInputStreamEx
{
public static void main(String[] args)
{
byte b[] = new byte [6]; // 6개의 원소를 저장할 수 있는 비어 있는 byte 배열 생성
try
{
FileInputStream fin = new FileInputStream("C:\\test\\news.txt");
int n=0, c;
while((c = fin.read())!= -1) // 문장의 끝에 도달하면 c는 -1을 리턴
{
b[n] = (byte)c; // 읽어온 바이너리 데이터(숫자)를 byte로 변환
n++; // 리스트의 다음 원소로
}
System.out.println("C:\\test\\news.txt에서 읽은 배열을 출력합니다.");
for(int i=0; i<b.length; i++) // 읽어온 바이너리 데이터 출력
System.out.print(b[i] + " ");
System.out.println();
fin.close(); // FileInputStreamEx 종료
}
catch(IOException e)
{
System.out.println( "C:\\test\\news.txt에서 읽지 못했습니다. 경로명을 체크해보세요");
}
}
}
// 파일,디렉터리 판별 및 디렉터리 안에 있는 파일들 목록 출력
import java.io.File;
public class FileEx
{
public static void listDirectory(File dir)
{
System.out.println("-----" + dir.getPath() + "의 서브 리스트입니다.-------");
File[] subFiles = dir.listFiles(); // dir의 파일 및 서브 디렉터리 리스트 확보
for(int i=0; i<subFiles.length; i++)
{
File f = subFiles[i]; // f = 서브 파일들
long t = f.lastModified(); // t = 최종 수정 날짜
System.out.print(f.getName()); // 파일명 출력
String res = "";
if(f.isFile()) // 파일인지 판별
res = "파일";
else // 디렉터리인지 판별
res = "디렉터리";
System.out.print("\t " + res);
System.out.print("\t파일 크기: " + f.length()); // 파일 크기 출력
System.out.printf("\t수정한 시간: %tb %td %ta %tT\n",t, t, t, t); // 수정시간 출력
}
}
public static void main(String[] args) // f1은 디텍터리 & 파일 판별, f2는 폴더에 해당 명의 디렉터리 없으면 생성 및 이름 변경
{
File f1 = new File("c:\\test\\news.txt");
System.out.println(f1.getPath() + ", " + f1.getParent() + ", " + f1.getName());
String res="";
if(f1.isFile()) // 파일인지 판별
res = "파일";
else if(f1.isDirectory()) // 디렉터리인지 판별
res = "디렉터리";
System.out.println(f1.getPath() + "은 " + res + "입니다.");
File f2 = new File("c:\\test\\java_sample");
if(!f2.exists())
{
f2.mkdir(); // test 폴더에 java_sample 디렉터리 생성
}
listDirectory(new File("c:\\test")); // 리스트 출력
f2.renameTo(new File("c:\\test\\javasample")); // java_sample -> javasample로 변경
listDirectory(new File("c:\\test")); // 리스트 출력
}
}
// 텍스트 파일 복사하기
import java.io.*;
public class TextCopyEx
{
public static void main(String[] args)
{
File src = new File("c:\\windows\\system.ini"); // 원본 파일 경로명
File dest = new File("c:\\test\\system.txt"); // 복사 파일 경로명
int c;
try {
FileReader fr = new FileReader(src);
FileWriter fw = new FileWriter(dest);
while((c = fr.read()) != -1) // 문자 하나 읽고
{
fw.write((char)c); // 문자 하나 쓰고
}
fr.close();
fw.close();
System.out.println(src.getPath()+ "를 " + dest.getPath()+ "로 복사하였습니다.");
} catch(IOException e)
{
System.out.println("파일 복사 오류");
}
}
}
// 바이너리 데이터 복사하기
import java.io.*;
public class BinaryCopyEx
{
public static void main(String[] args)
{
File src = new File("C:\\ITstudy\\1.jpg"); // 복사할 파일 경로
File dest = new File("c:\\test\\copyimg.jpg"); // 붙여넣기할 경로
int c;
try
{
FileInputStream fi = new FileInputStream(src); // 입력
FileOutputStream fo = new FileOutputStream(dest); // 출력
while((c = fi.read()) != -1) // 마지막부분에 다다르면 -1 반환 (이미지 읽기 반복)
{
fo.write((byte)c); // 읽은 이미지 작성하기
}
fi.close();
fo.close();
System.out.println(src.getPath()+ "를 " + dest.getPath()+ "로 복사하였습니다.");
}
catch(IOException e)
{
System.out.println("파일 복사 오류");
}
}
}
// 단어의 빈도수 세기
import java.util.HashMap;
import java.util.Map;
public class WordCount
{
public static void main(String[] args)
{
String str = "Java apple java: (java) is good programming Language. Yeah Right";
str = str.toLowerCase(); // 대소문자 구분 없이 하기 위해 소문자로 통일
str = str.replace(":", "").replace("(", "").replace(")", "").replace(":", ""); // 문자 아닌 기호 제거
String[] splitStr = str.split(" "); // 문자열을 공백 기준으로 잘라서 리스트에 저장
Map<String, Integer> hs = new HashMap<>();
for(int i =0; i<splitStr.length; i++) // 단어 빈도수 체크
{
if(hs.containsKey(splitStr[i]))
{
hs.put(splitStr[i], hs.get(splitStr[i]) + 1); // 단어(키)가 존재하면 해당 키의 value+1
}
else
{
hs.put(splitStr[i], 1); // 단어가 없으면 키와 value를 1로 초기화
}
}
for(String key : hs.keySet()) // :은 python의 in과 같은 개념
{
System.out.println(key + ": " + hs.get(key)); // 단어 빈도수 출력
}
}
}
'빅데이터 부트캠프 > Java' 카테고리의 다른 글
빅데이터 부트캠프 63일차 (0) | 2022.10.06 |
---|---|
빅데이터 부트캠프 62일차 (0) | 2022.10.05 |
빅데이터 부트캠프 38일차 (Java) (0) | 2022.08.26 |
빅데이터 부트캠프 36일차 (0) | 2022.08.24 |
빅데이터 부트캠프 35일차 (0) | 2022.08.23 |
댓글