• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2022 Google LLC
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.google.android.libraries.mobiledatadownload.file.openers;
17 
18 import com.google.android.libraries.mobiledatadownload.file.OpenContext;
19 import com.google.android.libraries.mobiledatadownload.file.Opener;
20 import com.google.android.libraries.mobiledatadownload.file.common.internal.Charsets;
21 import com.google.errorprone.annotations.CanIgnoreReturnValue;
22 import java.io.IOException;
23 import java.nio.charset.Charset;
24 
25 /** An opener that reads entire contents of file into a String. */
26 public final class ReadStringOpener implements Opener<String> {
27   private Charset charset = Charsets.UTF_8;
28 
ReadStringOpener()29   protected ReadStringOpener() {}
30 
create()31   public static ReadStringOpener create() {
32     return new ReadStringOpener();
33   }
34 
35   @CanIgnoreReturnValue
withCharset(Charset charset)36   public ReadStringOpener withCharset(Charset charset) {
37     this.charset = charset;
38     return this;
39   }
40 
41   @Override
open(OpenContext openContext)42   public String open(OpenContext openContext) throws IOException {
43     byte[] bytes = ReadByteArrayOpener.create().open(openContext);
44     return new String(bytes, charset);
45   }
46 }
47