1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  *
4  * This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License 2.0
6  * which accompanies this distribution, and is available at
7  * https://www.eclipse.org/legal/epl-2.0/
8  *
9  * SPDX-License-Identifier: EPL-2.0
10  *
11  * Contributors:
12  *     IBM Corporation - initial API and implementation
13  *******************************************************************************/
14 package org.eclipse.core.internal.localstore;
15 
16 import java.io.*;
17 
18 /**
19  * Given a target and a temporary locations, it tries to read the contents
20  * from the target. If a file does not exist at the target location, it tries
21  * to read the contents from the temporary location.
22  *
23  * @see SafeFileOutputStream
24  */
25 public class SafeFileInputStream extends FilterInputStream {
26 	protected static final String EXTENSION = ".bak"; //$NON-NLS-1$
27 	private static final int DEFAUT_BUFFER_SIZE = 2048;
28 
SafeFileInputStream(File file)29 	public SafeFileInputStream(File file) throws IOException {
30 		this(file.getAbsolutePath(), null);
31 	}
32 
33 	/**
34 	 * If targetPath is null, the file will be created in the default-temporary directory.
35 	 */
SafeFileInputStream(String targetPath, String tempPath)36 	public SafeFileInputStream(String targetPath, String tempPath) throws IOException {
37 		super(getInputStream(targetPath, tempPath, DEFAUT_BUFFER_SIZE));
38 	}
39 
40 	/**
41 	 * If targetPath is null, the file will be created in the default-temporary directory.
42 	 */
SafeFileInputStream(String targetPath, String tempPath, int bufferSize)43 	public SafeFileInputStream(String targetPath, String tempPath, int bufferSize) throws IOException {
44 		super(getInputStream(targetPath, tempPath, bufferSize));
45 	}
46 
getInputStream(String targetPath, String tempPath, int bufferSize)47 	private static InputStream getInputStream(String targetPath, String tempPath, int bufferSize) throws IOException {
48 		File target = new File(targetPath);
49 		if (!target.exists()) {
50 			if (tempPath == null)
51 				tempPath = target.getAbsolutePath() + EXTENSION;
52 			target = new File(tempPath);
53 		}
54 		return new BufferedInputStream(new FileInputStream(target), bufferSize);
55 	}
56 }
57