java - 无法写入 Java 中的文件

标签 java unix file-io ubuntu-14.04

我一直在尝试创建一个类,该类将遍历一个文件并根据它找到的值创建一个 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()(如果你不是,那么你应该在 finally block 中调用 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()));
        }
    }
}

最后,你的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()));
        }
    }
}

关于java - 无法写入 Java 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28619539/

相关文章:

python - 使用 Python 移动特定文件类型

c++ - fprintf - 指定路径

php - UNIX 日期操作

Bash:查找具有最大行数的文件

java - java中带有gui的接口(interface)类?

java - com.fasterxml.jackson.core.JsonParseException : Unrecognized character escape 'U' (code 85)

linux - 我应该在哪个操作系统文件夹中创建一个隐藏文件来表示我的客户的许可证已过期?

c++ - 如何在 qt 中执行异步文件 io?

java - 使用 php 打开进程并在请求之间保持打开状态

java - 从其他线程更新 Swing GUI