001    /*
002     * Copyright 2005 [ini4j] Development Team
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    
017    package org.ini4j;
018    
019    import java.io.*;
020    import java.util.prefs.*;
021    
022    public class IniFile extends IniPreferences
023    {
024        public static enum Mode {RO,WO,RW};
025        
026        private Mode _mode;
027        private File _file;
028    
029        public IniFile(File file, Mode mode) throws BackingStoreException
030        {
031            super(new Ini());
032            _file = file;
033            _mode = mode;
034            
035            if ( (_mode == Mode.RO) || ( (_mode != Mode.WO) && _file.exists() ) )
036            {
037                sync();
038            }
039        }
040    
041        public IniFile(File file) throws BackingStoreException
042        {
043            this(file, Mode.RO);
044        }
045        
046        public Mode getMode()
047        {
048            return _mode;
049        }
050        
051        public File getFile()
052        {
053            return _file;
054        }
055    
056        public void sync() throws BackingStoreException
057        {
058            if ( _mode == Mode.WO )
059            {
060                throw new BackingStoreException("write only instance");
061            }
062            
063            try
064            {
065                synchronized (lock)
066                {
067                    getIni().load(_file.toURL());
068                }
069            }
070            catch (Exception x)
071            {
072                throw new BackingStoreException(x);
073            }
074        }
075    
076        public void flush() throws BackingStoreException
077        {
078            if ( _mode == Mode.RO )
079            {
080                throw new BackingStoreException("read only instance");
081            }
082    
083            try
084            {
085                synchronized (lock)
086                {
087                    getIni().store(new FileWriter(_file));
088                }
089            }
090            catch (Exception x)
091            {
092                throw new BackingStoreException(x);
093            }
094        }
095    }