无法写入 Java 中的文件

Unable to write to a file in Java

我一直在尝试创建一个 class 它将遍历一个文件并根据它找到的值创建一个 HashMap 并且还可以将一个 HashMap 写入同一个文件,其中更改的值与新的合并和已经存在的。将文件读入 HashMap 是可行的,但是,当我尝试使用不同的值和键将所述 HashMap 写回文件时,文件不会发生任何变化。 澄清一下,我使用的是 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();
  }
}

我正在调用方法

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();
}

使用GEdit我可以看出文件正在被修改,但文件实际上没有任何变化,我已经确保文件是可写和可读的。我真的很困惑为什么会发生这种情况,因为甚至没有抛出异常。

更改命令的顺序。在您创建 文件后 创建文件 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 ) );

此外,如果您使用的是 Java 7+,我建议您利用 try-with-resources Statementclose()(如果不是,那么您应该调用 close()finally 块中)

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()));
        }
    }
}

最后,你的FileWriter(File) 构造函数保证创建一个新文件(因为你没有传入追加)。因此,你真的应该使用像

这样的东西
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()));
        }
    }
}