• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2024 The Android Open Source Project
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 
17 package android.util;
18 
19 import java.io.BufferedWriter;
20 import java.io.IOException;
21 import java.io.OutputStreamWriter;
22 import java.io.PrintWriter;
23 import java.nio.charset.Charset;
24 
25 
26 /**
27  * {@link PrintWriter} for {@link AtomicFile}
28  * In order to "commit" the new content to the file, call {@link #markSuccess()} then
29  * {@link #close()}. Calling{@link #markSuccess()} alone won't update the file.
30  * This class does not confer any file locking semantics. Do not use this class when the file may be
31  * accessed or modified concurrently by multiple threads or processes. The caller is responsible for
32  * ensuring appropriate mutual exclusion invariants whenever it accesses the file.
33  * @hide
34  */
35 @android.ravenwood.annotation.RavenwoodKeepWholeClass
36 public class AtomicFilePrintWriter extends PrintWriter {
37     private final AtomicFileOutputStream mAtomicFileOutStream;
38 
39     /**
40      * Construct from {@link AtomicFile} with {@link BufferedWriter} default buffer size.
41      */
AtomicFilePrintWriter(AtomicFile atomicFile, Charset charset)42     public AtomicFilePrintWriter(AtomicFile atomicFile, Charset charset)
43             throws IOException {
44         this(new AtomicFileOutputStream(atomicFile), charset);
45     }
46 
47     /**
48      * Create from {@link AtomicFileOutputStream}.
49      */
AtomicFilePrintWriter(AtomicFileOutputStream outStream, Charset charset)50     public AtomicFilePrintWriter(AtomicFileOutputStream outStream, Charset charset) {
51         super(new OutputStreamWriter(outStream, charset));
52         mAtomicFileOutStream = outStream;
53     }
54 
55     /**
56      * When write is successful this needs to be called to flush the buffer and mark the writing as
57      * successful.
58      */
markSuccess()59     public void markSuccess() throws IOException {
60         flush();
61         mAtomicFileOutStream.markSuccess();
62     }
63 
64     /**
65      * Creates string representation of the object.
66      */
67     @Override
toString()68     public String toString() {
69         return "AtomicFilePrintWriter[" + mAtomicFileOutStream + "]";
70     }
71 }
72