learn/data structure

파일 (File)

사겅이 2023. 9. 24. 07:44

출처 : https://sungwookkang.com/199

데이터를 저장하고 관리하는 방법

 

  • 순차 파일(Sequential File)
    순차 파일은 데이터 레코드가 논리적인 순서대로 연속적인 블록에 저장되는 파일 구조로 데이터를 읽거나 쓸 때 처음부터 순차적으로 접근해야 함

출처 : https://www.baeldung.com/cs/file-access

package datastructure.nonlinear;

import java.io.*;

public class SequentialFileTest {
    public static void main(String[] args) {
        try {
            // 파일 생성 또는 열기
            FileWriter fw = new FileWriter("sequential_file.txt");
            BufferedWriter bw = new BufferedWriter(fw);

            // 데이터 쓰기
            bw.write("첫 번째 레코드");
            bw.newLine(); // 다음 레코드를 위해 줄 바꿈
            bw.write("두 번째 레코드");

            // 파일 닫기
            bw.close();

            // 파일 읽기
            FileReader fr = new FileReader("sequential_file.txt");
            BufferedReader br = new BufferedReader(fr);
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

            // 파일 닫기
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 색인 파일(Indexed File)
    색인 파일은 데이터 레코드를 정렬하고 색인을 생성하여 데이터를 검색 및 엑세스하기 쉽게 하는 파일 구조

출처 : https://www.baeldung.com/cs/file-access

<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-core</artifactId>
    <version>8.12.1</version> <!-- 사용 가능한 최신 버전을 선택하세요. -->
</dependency>
package datastructure.nonlinear;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.IOException;
import java.nio.file.Paths;

public class IndexedFileTest {
    public static void main(String[] args) {
        String indexPath = "index"; // 색인 파일을 저장할 디렉터리 경로
        String textToIndex = "This is a sample text to be indexed."; // 색인할 텍스트

        try {
            Directory directory = FSDirectory.open(Paths.get(indexPath));
            Analyzer analyzer = new StandardAnalyzer();
            IndexWriterConfig config = new IndexWriterConfig(analyzer);
            IndexWriter indexWriter = new IndexWriter(directory, config);

            Document document = new Document();
            document.add(new Field("content", textToIndex, Field.Store.YES, Field.Index.ANALYZED));
            indexWriter.addDocument(document);

            indexWriter.close();
            directory.close();

            System.out.println("색인 파일이 생성되었습니다.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 직접 파일(Direct Access 또는 Random Access File)
    직접 파일은 데이터 레코드를 논리적인 순서와 상관없이 직접 엑세스할 수 있는 파일 구조

출처 : https://www.baeldung.com/cs/file-access

package datastructure.nonlinear;

import java.io.*;

public class DirectAccessFileTest {
    public static void main(String[] args) {
        try {
            // 파일 생성 또는 열기
            RandomAccessFile file = new RandomAccessFile("direct_access_file.dat", "rw");

            // 데이터 쓰기
            file.writeUTF("첫 번째 레코드");
            file.writeUTF("두 번째 레코드");

            // 특정 위치의 데이터 읽기
            file.seek(0); // 첫 번째 레코드로 이동
            String record1 = file.readUTF();
            file.seek(1); // 두 번째 레코드로 이동
            String record2 = file.readUTF();

            System.out.println(record1);
            System.out.println(record2);

            // 파일 닫기
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

'learn > data structure' 카테고리의 다른 글

해쉬맵 (HashMap)과 해쉬테이블 (HashTable)  (0) 2023.09.24
그래프 (Graph)  (0) 2023.09.24
트리 (Tree)  (0) 2023.09.24
데크 (Deque)  (0) 2023.09.24
큐 (Queue)  (0) 2023.09.24