简体   繁体   English

无法用Java写入文件

[英]Unable to write to a file in Java

I have been attempting to create a class that will go through a file and create a HashMap based on the values it finds and that can also write a HashMap to the same file with changed values incorporated with new and already existing ones. 我一直在尝试创建一个类,该类将遍历文件并根据其找到的值创建一个HashMap,并且还可以将HashMap写入具有相同新值和现有值的更改值的同一文件中。 The reading of the file into a HashMap is working, however, when I attempt to write said HashMap back to the file with different values and keys, the file does not change what so ever. 将该文件读入HashMap是可行的,但是,当我尝试使用不同的值和键将所说的HashMap写回到该文件时,该文件不会改变。 Just for clarification, I am on a UNIX-Style system: Ubuntu 14.10 为了澄清起见,我使用的是UNIX风格的系统:Ubuntu 14.10

public class FConfig {
  public FConfig( String pathToFile ) throws IOException {
    config = new File( pathToFile );
    if( !config.exists() ) {
      config.createNewFile();
    }
  }
  public FConfig( File file ) throws IOException {
    if( !file.isFile() ) {
      throw new IllegalArgumentException();
    }
    config = new File( file.getAbsolutePath() );
    if( !config.exists() ) {
      config.createNewFile();
    }
  }
  private final File config;
  private BufferedReader fileIn;
  private BufferedWriter fileOut;

  public HashMap<String, String> loadAllProperties() throws IOException {
    fileIn = new BufferedReader( new FileReader( config ) );
    config.setReadable( true );
    HashMap<String, String> props = new HashMap<>();
    String line;
    while( ( line = fileIn.readLine() ) != null ) {
      if( line.contains( "=" ) ) {
        props.put( line.split( "=" )[ 0 ], line.split( "=" )[ 1 ] );
      }
    }
    return props;
  }
  public void writeAllProperties( HashMap<String, String> newProps ) throws IOException {
    fileOut = new BufferedWriter( new FileWriter( config ) );
    HashMap<String, String> props = loadAllProperties();
    props.putAll( newProps );
    config.delete();
    config.createNewFile();
    config.setWritable( true );
    System.out.println( config.canWrite() );
    for( Entry<String, String> entry : props.entrySet() ) {
      System.out.println( entry.getKey() + "=" + entry.getValue() );
      fileOut.write( String.format( "%1$s=%2$s", entry.getKey(), entry.getValue() ) );
    }
    fileOut.close();
  }
}

and I am calling the method 我在叫方法

FConfig c = new FConfig( new File( System.getProperty( "user.home" ), "fConfig.cfg" ).getAbsolutePath() );

HashMap<String, String> props = new HashMap<>();
props.put( "a", "value0" );
props.put( "c", "value1" );
props.put( "b", "value2" );
for( Entry<String, String> e : c.loadAllProperties().entrySet() ) {
  System.out.println( e.getKey() + ":" + e.getValue() );
}
try {
  c.writeAllProperties( props );
} catch( Exception e ) {
  e.printStackTrace();
}

Using GEdit I can tell that the file is being modified, but nothing actually changes in the file, I have ensured that the file is writable and readable. 使用GEdit,我可以确定文件已被修改,但是文件中实际上没有任何更改,因此我确保了文件可写且可读。 I am truly confused as to why this is happening as not even an exception is thrown. 我真的很困惑为什么会发生这种情况,甚至没有引发异常。

Change the order of your commands. 更改命令的顺序。 Create the FileWriter on your file after you create it. 创建文件 ,在文件上创建FileWriter

public void writeAllProperties( HashMap<String, String> newProps ) throws IOException {
    // fileOut = new BufferedWriter( new FileWriter( config ) );
    HashMap<String, String> props = loadAllProperties();
    props.putAll( newProps );
    config.delete();
    config.createNewFile();
    config.setWritable( true );
    // You just created a new file.
    fileOut = new BufferedWriter( new FileWriter( config ) );

Also, if you're using Java 7+ I suggest you take advantage of the try-with-resources Statement to close() (and if you aren't, then you should call close() in a finally block) 另外,如果您使用的是Java 7+,建议您利用try-with-resources语句close() (如果不是,则应在finally块中调用close() )。

public void writeAllProperties(HashMap<String, String> newProps)
        throws IOException {
    // fileOut = new BufferedWriter(new FileWriter(config));
    HashMap<String, String> props = loadAllProperties();
    props.putAll(newProps);
    config.delete();
    config.createNewFile();
    config.setWritable(true);
    try (BufferedWriter fileOut = new BufferedWriter(new FileWriter(config))) {
        System.out.println(config.canWrite());
        for (Entry<String, String> entry : props.entrySet()) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
            fileOut.write(String.format("%1$s=%2$s", entry.getKey(),
                    entry.getValue()));
        }
    }
}

Finally , your FileWriter(File) constructor is guaranteed to create a new file (since you aren't passing in append). 最后 ,保证您的FileWriter(File)构造函数可以创建一个新文件(因为您没有在append中传递)。 As such, you should really be using something like 因此,您实际上应该使用类似

public void writeAllProperties(HashMap<String, String> newProps)
        throws IOException {
    // fileOut = new BufferedWriter(new FileWriter(config));
    HashMap<String, String> props = loadAllProperties();
    props.putAll(newProps);
    if (!config.canWrite()) { // <-- to check if it is writable
        return;
    }
    try (BufferedWriter fileOut = new BufferedWriter(new FileWriter(config))) {
        System.out.println(config.canWrite());
        for (Entry<String, String> entry : props.entrySet()) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
            fileOut.write(String.format("%1$s=%2$s", entry.getKey(),
                    entry.getValue()));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM