Development Tip

자바 : 텍스트 파일 읽는 방법

yourdevel 2020. 9. 25. 23:43
반응형

자바 : 텍스트 파일 읽는 방법


공백으로 구분 된 값이 포함 된 텍스트 파일을 읽고 싶습니다. 값은 정수입니다. 어떻게 읽고 배열 목록에 넣을 수 있습니까?

다음은 텍스트 파일 내용의 예입니다.

1 62 4 55 5 6 77

나는 그것을 arraylist에 [1, 62, 4, 55, 5, 6, 77]. Java에서 어떻게 할 수 있습니까?


를 사용 Files#readAllLines()하여 텍스트 파일의 모든 줄을 List<String>.

for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
    // ...
}

튜토리얼 : 기본 I / O> 파일 I / O> 텍스트 파일 읽기, 쓰기 및 만들기


정규식에 따라 in 부분 String#split()을 분할하는 데 사용할 수 있습니다 String.

for (String part : line.split("\\s+")) {
    // ...
}

자습서 : 숫자 및 문자열> 문자열> 문자열에서 문자 조작


당신은 사용할 수 있습니다 Integer#valueOf()을 변환 StringInteger.

Integer i = Integer.valueOf(part);

튜토리얼 : 숫자와 문자열> 문자열> 숫자와 문자열 간 변환


List#add()요소를 추가하는 데 사용할 수 있습니다 List.

numbers.add(i);

자습서 : 인터페이스> 목록 인터페이스


따라서 간단히 말해서 (파일에 빈 줄이나 후행 / 선행 공백이 없다고 가정).

List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
    for (String part : line.split("\\s+")) {
        Integer i = Integer.valueOf(part);
        numbers.add(i);
    }
}

이미 Java 8을 사용하는 경우 .NET으로 시작 하는 Stream API사용할 수도 있습니다 Files#lines().

List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
    .map(line -> line.split("\\s+")).flatMap(Arrays::stream)
    .map(Integer::valueOf)
    .collect(Collectors.toList());

자습서 : Java 8 스트림으로 데이터 처리


Java 1.5는 파일 및 스트림의 입력을 처리하기위한 Scanner 클래스를 도입했습니다 .

파일에서 정수를 가져 오는 데 사용되며 다음과 같습니다.

List<Integer> integers = new ArrayList<Integer>();
Scanner fileScanner = new Scanner(new File("c:\\file.txt"));
while (fileScanner.hasNextInt()){
   integers.add(fileScanner.nextInt());
}

그래도 API를 확인하십시오. 다른 유형의 입력 소스, 다른 구분 기호 및 다른 데이터 유형을 처리하기위한 더 많은 옵션이 있습니다.


이 예제 코드는 Java에서 파일을 읽는 방법을 보여줍니다.

import java.io.*;

/**
 * This example code shows you how to read file in Java
 *
 * IN MY CASE RAILWAY IS MY TEXT FILE WHICH I WANT TO DISPLAY YOU CHANGE WITH YOUR   OWN      
 */

 public class ReadFileExample 
 {
    public static void main(String[] args) 
    {
       System.out.println("Reading File from Java code");
       //Name of the file
       String fileName="RAILWAY.txt";
       try{

          //Create object of FileReader
          FileReader inputFile = new FileReader(fileName);

          //Instantiate the BufferedReader Class
          BufferedReader bufferReader = new BufferedReader(inputFile);

          //Variable to hold the one line data
          String line;

          // Read file line by line and print on the console
          while ((line = bufferReader.readLine()) != null)   {
            System.out.println(line);
          }
          //Close the buffer reader
          bufferReader.close();
       }catch(Exception e){
          System.out.println("Error while reading file line by line:" + e.getMessage());                      
       }

     }
  }

이 예를보고 직접 시도해보십시오.

import java.io.*;

public class ReadFile {

    public static void main(String[] args){
        String string = "";
        String file = "textFile.txt";

        // Reading
        try{
            InputStream ips = new FileInputStream(file);
            InputStreamReader ipsr = new InputStreamReader(ips);
            BufferedReader br = new BufferedReader(ipsr);
            String line;
            while ((line = br.readLine()) != null){
                System.out.println(line);
                string += line + "\n";
            }
            br.close();
        }
        catch (Exception e){
            System.out.println(e.toString());
        }

        // Writing
        try {
            FileWriter fw = new FileWriter (file);
            BufferedWriter bw = new BufferedWriter (fw);
            PrintWriter fileOut = new PrintWriter (bw);
                fileOut.println (string+"\n test of read and write !!");
            fileOut.close();
            System.out.println("the file " + file + " is created!");
        }
        catch (Exception e){
            System.out.println(e.toString());
        }
    }
}

재미로, 내가 좋아하는 모든 라이브러리를 이미 사용하고있는 실제 프로젝트에서 수행 할 작업이 있습니다 (이 경우 Guava , 이전에 Google Collections ).

String text = Files.toString(new File("textfile.txt"), Charsets.UTF_8);
List<Integer> list = Lists.newArrayList();
for (String s : text.split("\\s")) {
    list.add(Integer.valueOf(s));
}

이점 : 유지 관리 할 자체 코드가 많지 않습니다 (예 : this 과 대조 ). 편집 :이 경우 tschaible의 스캐너 솔루션에 더 이상 코드 가 없다는 점은 주목할 가치가 있습니다!

Drawback: you obviously may not want to add new library dependencies just for this. (Then again, you'd be silly not to make use of Guava in your projects. ;-)


Use Apache Commons (IO and Lang) for simple/common things like this.

Imports:

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;

Code:

String contents = FileUtils.readFileToString(new File("path/to/your/file.txt"));
String[] array = ArrayUtils.toArray(contents.split(" "));

Done.


Using Java 7 to read files with NIO.2

Import these packages:

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

This is the process to read a file:

Path file = Paths.get("C:\\Java\\file.txt");

if(Files.exists(file) && Files.isReadable(file)) {

    try {
        // File reader
        BufferedReader reader = Files.newBufferedReader(file, Charset.defaultCharset());

        String line;
        // read each line
        while((line = reader.readLine()) != null) {
            System.out.println(line);
            // tokenize each number
            StringTokenizer tokenizer = new StringTokenizer(line, " ");
            while (tokenizer.hasMoreElements()) {
                // parse each integer in file
                int element = Integer.parseInt(tokenizer.nextToken());
            }
        }
        reader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

To read all lines of a file at once:

Path file = Paths.get("C:\\Java\\file.txt");
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);

All the answers so far given involve reading the file line by line, taking the line in as a String, and then processing the String.

There is no question that this is the easiest approach to understand, and if the file is fairly short (say, tens of thousands of lines), it'll also be acceptable in terms of efficiency. But if the file is long, it's a very inefficient way to do it, for two reasons:

  1. Every character gets processed twice, once in constructing the String, and once in processing it.
  2. The garbage collector will not be your friend if there are lots of lines in the file. You're constructing a new String for each line, and then throwing it away when you move to the next line. The garbage collector will eventually have to dispose of all these String objects that you don't want any more. Someone's got to clean up after you.

If you care about speed, you are much better off reading a block of data and then processing it byte by byte rather than line by line. Every time you come to the end of a number, you add it to the List you're building.

It will come out something like this:

private List<Integer> readIntegers(File file) throws IOException {
    List<Integer> result = new ArrayList<>();
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    byte buf[] = new byte[16 * 1024];
    final FileChannel ch = raf.getChannel();
    int fileLength = (int) ch.size();
    final MappedByteBuffer mb = ch.map(FileChannel.MapMode.READ_ONLY, 0,
            fileLength);
    int acc = 0;
    while (mb.hasRemaining()) {
        int len = Math.min(mb.remaining(), buf.length);
        mb.get(buf, 0, len);
        for (int i = 0; i < len; i++)
            if ((buf[i] >= 48) && (buf[i] <= 57))
                acc = acc * 10 + buf[i] - 48;
            else {
                result.add(acc);
                acc = 0;
            }
    }
    ch.close();
    raf.close();
    return result;
}

The code above assumes that this is ASCII (though it could be easily tweaked for other encodings), and that anything that isn't a digit (in particular, a space or a newline) represents a boundary between digits. It also assumes that the file ends with a non-digit (in practice, that the last line ends with a newline), though, again, it could be tweaked to deal with the case where it doesn't.

It's much, much faster than any of the String-based approaches also given as answers to this question. There is a detailed investigation of a very similar issue in this question. You'll see there that there's the possibility of improving it still further if you want to go down the multi-threaded line.


read the file and then do whatever you want java8 Files.lines(Paths.get("c://lines.txt")).collect(Collectors.toList());

참고URL : https://stackoverflow.com/questions/2788080/java-how-to-read-a-text-file

반응형