簡體   English   中英

無法用Java寫入文件

[英]Unable to write to a file in Java

我一直在嘗試創建一個類,該類將遍歷文件並根據其找到的值創建一個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語句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()));
        }
    }
}

最后 ,保證您的FileWriter(File)構造函數可以創建一個新文件(因為您沒有在append中傳遞)。 因此,您實際上應該使用類似

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