2010-02-10 57 views

回答

1

否。将文件的其余部分复制到另一个文件中,删除旧文件并重命名新文件。

2

你能做到这一点

/** 
* Replaces the caracter at the {@code index} position with the {@code newChar} 
* character 
* @param f file to modify 
* @param index of the character to replace 
* @param newChar new character 
* @throws FileNotFoundException if file does not exist 
* @throws IOException if something bad happens 
*/ 
private static void replaceChar(File f, int index, char newChar) 
     throws FileNotFoundException, IOException { 

    int fileLength = (int) f.length(); 

    if (index < 0 || index > fileLength - 1) { 
     throw new IllegalArgumentException("Invalid index " + index); 
    } 

    byte[] bt = new byte[(int) fileLength]; 
    FileInputStream fis = new FileInputStream(f); 
    fis.read(bt); 
    StringBuffer sb = new StringBuffer(new String(bt)); 

    sb.setCharAt(index, newChar); 

    FileOutputStream fos = new FileOutputStream(f); 
    fos.write(sb.toString().getBytes()); 
    fos.close(); 
} 

但是请注意,它不会非常大的文件为f.length()被铸造为int工作。对于那些你应该使用通常的方法来阅读整个文件并将其扔到另一个文件上。