001 /*
002 * Copyright 2005,2009 Ivan SZKIBA
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016 package org.ini4j;
017
018 import java.io.File;
019 import java.io.FileWriter;
020
021 import java.util.prefs.BackingStoreException;
022
023 public class IniFile extends IniPreferences
024 {
025 public static enum Mode
026 {
027 RO,
028 WO,
029 RW
030 }
031
032 private final File _file;
033 private final Mode _mode;
034
035 public IniFile(File file) throws BackingStoreException
036 {
037 this(file, Mode.RO);
038 }
039
040 public IniFile(File file, Mode mode) throws BackingStoreException
041 {
042 super(new Ini());
043 _file = file;
044 _mode = mode;
045 if ((_mode == Mode.RO) || ((_mode != Mode.WO) && _file.exists()))
046 {
047 sync();
048 }
049 }
050
051 public File getFile()
052 {
053 return _file;
054 }
055
056 public Mode getMode()
057 {
058 return _mode;
059 }
060
061 @Override public void flush() throws BackingStoreException
062 {
063 if (_mode == Mode.RO)
064 {
065 throw new BackingStoreException("read only instance");
066 }
067
068 try
069 {
070 synchronized (lock)
071 {
072 FileWriter writer = new FileWriter(_file);
073
074 try
075 {
076 getIni().store(writer);
077 }
078 finally
079 {
080 writer.close();
081 }
082 }
083 }
084 catch (Exception x)
085 {
086 throw new BackingStoreException(x);
087 }
088 }
089
090 @Override public void sync() throws BackingStoreException
091 {
092 if (_mode == Mode.WO)
093 {
094 throw new BackingStoreException("write only instance");
095 }
096
097 try
098 {
099 synchronized (lock)
100 {
101 getIni().load(_file.toURI().toURL());
102 }
103 }
104 catch (Exception x)
105 {
106 throw new BackingStoreException(x);
107 }
108 }
109 }