BufferedReader readLine이 null을 반환합니다.

레오나르도 알베스 마차도

읽고 싶은 9개의 파일이 포함된 zip 파일이 있습니다. 그래서 다음 기능을 구현했습니다.

public static Map<String, BufferedReader> unzipFile(InputStream zippedFile) throws IOException {
  ZipInputStream zipInputStream = new ZipInputStream(zippedFile);
  HashMap<String, BufferedReader> result = new HashMap<>(9);
  for (ZipEntry zipEntry = zipInputStream.getNextEntry(); zipEntry != null; zipEntry = zipInputStream.getNextEntry()) {
    if (zipEntry.isDirectory()) {
      continue;
    }
    result.put(zipEntry.getName(), new BufferedReader(new InputStreamReader(zipInputStream)));
  }
  return result;
}

동일한 클래스의 다른 서명(동일한 메소드 호출):

  public static Map<String, BufferedReader> unzipFile(String zippedFile) throws IOException {
    return unzipFile(new File(zippedFile));
  }

  public static Map<String, BufferedReader> unzipFile(File zippedFile) throws IOException {
    return unzipFile(new FileInputStream(zippedFile));
  }

내 생각은 Map이 메서드에서 반환되는 값 을 가져 와서 내 코드의 다른 곳에서 읽을 수 있도록 하는 것이었습니다. 문제는 이 메서드 result.get("filename").readLine()에서 for루프 외부에서 호출할 때마다 null.

다음은 이 방법에 대한 간단한 단위 테스트입니다. 현재 마지막 단계에서 실패하고 있습니다 Assert.assertNotNull.

  @Test
  public void unzipFileTest() throws Exception  {
    Map<String, BufferedReader> result = FileHandlerUtility.unzipFile(TestUtil.FILE_SAMPLE_NAME);
    Assert.assertNotNull(result);
    Assert.assertEquals(result.size(), 9);
    Assert.assertNotNull(result.get("Car.txt"));
    Assert.assertNotNull(result.get("Client.txt"));
    Assert.assertNotNull(result.get("Client.txt").readLine());
  }

디버깅할 때 for루프 내에서 파일의 내용을 가져올 수 있다는 것을 알았기 때문에 생성된 변수의 범위와 관련된 것이 있을 수 있습니다 . 하지만 이 zip 추출 방식과 콘텐츠를 가져와서 파싱하는 방식을 혼용하고 싶지는 않았습니다. 또한 추출된 파일을 디스크에 저장하고 나중에 다시 열고 싶지 않습니다.

그래서, 내가 어떻게이 문제를 채울 수 MapBufferedReader에 NULL을 반환하지 않을의 readLine호출?

user11364257

ZipInputStream

진입 포인터를 반복할 때마다 ZipInputStream 객체당 하나의 스트림만 허용되므로 진입 포인터를 잃게 됩니다.

try (ZipInputStream is = new ZipInputStream(Zippy.class.getResourceAsStream("file.zip"))) {
            ZipEntry entry;
            while ((entry = is.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    // do your logic here (get the entry name)
                }                
                is.closeEntry();
        }
    }

javadoc에서 :

closeEntry() -Closes the current ZIP entry and positions the stream for reading the next entry.

getNextEntry() - Reads the next ZIP file entry and positions the stream at the beginning of the entry data.

기본적으로 주어진 시간에 하나의 항목만 열 수 있습니다.

따라서 현재 수행 중인 작업을 수행하려는 경우 할 수 있는 최선은 zip 항목의 이름을 저장하고 ZipInputStream을 반복하여 포인터를 올바른 위치로 이동한 다음 ZipInputStream.read()를 사용하여 가져올 수 있습니다. 바이트.

압축 파일

ZipInputStream 대신에 ZipFile 객체를 사용할 수 있다면 원하는 작업을 수행할 수 있습니다.

 static void loadMap() throws IOException {
    ZipFile file = new ZipFile("testzip.zip");
    Enumeration<? extends ZipEntry> entries = file.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (!entry.isDirectory()) {
            streamMap.put(entry.getName(), new BufferedReader(new InputStreamReader(file.getInputStream(entry))));
        }

    }

}

public static void main(String[] args) throws IOException {
    loadMap();

    Iterator<BufferedReader> iter = streamMap.values().iterator();
    while (iter.hasNext()) {            
        BufferedReader reader = iter.next();
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    }
}


OUTPUT:
file 2: First line!
file 2: Second Line!
file 1: First line!
file 1 : Second Line!
BUILD SUCCESSFUL (total time: 0 seconds)

zip 파일 참조를 유지하고 file.close();작업이 끝나면 호출하는 것을 기억해야 합니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

bufferedReader.readLine ();을 수행 할 때 null이 반환되는 이유는 무엇입니까? Windows cmd 및 powershell에서?

BufferedReader는 읽는 스트림이 위치 0에 있더라도 null을 반환합니다.

BufferedReader.ready () 메서드는 readLine () 메서드가 NULL을 반환하지 않도록 보장합니까?

C# process.StandardOutput.ReadLine()이 null을 반환합니다.

Java의 BufferedReader.readLine ()이 전체 파일을 메모리에 저장합니까?

Java BufferedReader.readLine()이 사용자 입력을 기다리지 않음

BufferedReader.readline ()은 출력을 차단합니다.

BufferedReader가 아직 null이 아닙니다.

@AuthenticationPrincipal이 null을 반환합니다.

목록이 null을 반환합니다.

GetManifestResourceStream이 NULL을 반환합니다.

Linq식이 null을 반환합니다.

ClassLoader getResourceAsStream이 null을 반환합니다.

큰 Json이 null을 반환합니다.

getResourceAsStream이 null을 반환합니다.

mockito stubbing이 null을 반환합니다.

JUnit getMethodName이 null을 반환합니다.

getResourceAsStream이 null 값을 반환합니다.

Listview getItemAt이 null을 반환합니다.

JRaw SelectToken이 null을 반환합니다.

getLastKnownLocation이 null을 반환합니다.

Android SwipeRefreshLayout이 null을 반환합니다.

FindParentWindow (this) .Name이 null을 반환합니다.

FirebaseInstanceIdService getToken이 null을 반환합니다.

LEFT JOIN이 null을 반환합니다.

API URL이 Null을 반환합니다.

Django GraphQL이 null을 반환합니다.

Firestore onSnapshot()이 null을 반환합니다.

getUniformLocation이 null을 반환합니다.

TOP 리스트

  1. 1

    PrematureCloseException : 연결이 너무 일찍 닫혔습니다.

  2. 2

    MDRotatingPieChart를 회전하면 각도 대신 x / y 위치가 변경됩니다.

  3. 3

    c # 웹 사이트에서 텍스트를 복사하는 방법 (소스 코드 아님)

  4. 4

    jfreecharts에서 x 및 y 축 선을 조정하는 방법

  5. 5

    ArrayBufferLike의 typescript 정의의 깊은 의미

  6. 6

    Ionic 2 로더가 적시에 표시되지 않음

  7. 7

    복사 / 붙여 넣기 비활성화

  8. 8

    Google Play Console에서 '예기치 않은 오류가 발생했습니다. 나중에 다시 시도해주세요. (7100000)'오류를 수정하는 방법은 무엇입니까?

  9. 9

    정점 셰이더에서 카메라에서 개체까지의 XY 거리

  10. 10

    QT Designer를 사용하여 GUI에 이미지 삽입

  11. 11

    java Apache POI Word 기존 테이블 셀 스타일 및 서식이있는 행 삽입

  12. 12

    Kubernetes Horizontal Pod Autoscaler (HPA) 테스트

  13. 13

    Android Kotlin은 다른 활동에서 함수를 호출합니다.

  14. 14

    C # HttpWebRequest 기본 연결이 닫혔습니다. 전송시 예기치 않은 오류가 발생했습니다.

  15. 15

    어떻게 같은 CustomInfoWindow 다른 이벤트를 할 수 있습니다

  16. 16

    rclone으로 원격 디렉토리의 모든 파일을 삭제하는 방법은 무엇입니까?

  17. 17

    dataSnapShot.getValue () 반환 데이터베이스에 그겁니다 데이터 종료 널 (null)

  18. 18

    ORA-12557 TNS : 프로토콜 어댑터를로드 할 수 없습니다

  19. 19

    JNDI를 사용하여 Spring Boot에서 다중 데이터 소스 구성

  20. 20

    다음 컨트롤이 추가되었지만 사용할 수 없습니다.

  21. 21

    C # Asp.net 웹 API-JSON / XML 변환기 API 만들기

뜨겁다태그

보관