重写程序已使用的文件

时间:2011-07-05 13:42:48

标签: java file stream rewrite erase

我想知道是否有办法确定程序中是否有任何流?

我正在使用我的一些代码和其他代码,我的目标是能够多次写入同一个文件,擦除它并每次都重写。但是,我想某个地方,属于这个其他组的代码可能忘记关闭流,或者Java无法处理它,也许?它总是写在文件的末尾,而不是在空白文件的开头。它不会删除,如果已经被程序打开,我就无法重命名。

如果它是一个开放流问题,我想关闭流(我已经通过代码,似乎无法找到开放流)。或者如果Java无法处理它,有没有一种好的方法(除了制作破坏方法)让我能够重置/杀死要重新设置的对象?

或者有没有办法可能......将文件设置为null并删除它?或者我应该尝试打开文件,将其擦除并将偏移设置为0?

任何提示都会很好

2 个答案:

答案 0 :(得分:0)

以下是一些可能对您有用的好代码:

public void writeToNewFile(String filePath, String data)
{
    PrintWriter writer;
    File file;
    try
    {
        file = new File(filePath);
        file.createNewFile();
        writer = new PrintWriter(new FileWriter(file));
        writer.println(data);
        writer.flush();
        writer.close();
     }catch(Exception e){e.printStackTrace();}
     writer = null;
     file = null;
     \\setting file & writer to null releases all the system resources and allows the files to be accessed again later
}

//this will write to end of file
public void writeToExistingFile(String filePath, String data)
{
    PrintWriter writer;
    File file;
    try
    {
        file = new File(filePath);
        if(!file.exists())
            file.createNewFile();
        writer = new PrintWriter(new FileWriter(file,true));
        writer.println(data);
        writer.flush();
        writer.close();
     }catch(Exception e){e.printStackTrace();}
     writer = null;
     file = null;
     \\setting file & writer to null releases all the system resources and allows the files to be accessed again later
}

public String[] readFile(String filePath)
{
    String data[];
    Iterator<String> it;
    ArrayList<String> dataHolder = new ArrayList<String>();
    BufferedReader reader;
    File file;
    try
    {
        file = new File(filePath);
        reader = new BufferedReader(new FileReader(file));

        int lines = 0;
        while(reader.ready())
        {
            lines++;
            dataHolder.add(reader.readLine());
        }

        data = new String[lines];
        it = dataHolder.iterator();
        for(int x=0;it.hasNext();x++)
            data[x] = it.next();

        reader.close();
     }catch(Exception e){e.printStackTrace();}
     reader = null;
     file = null;
     \\setting file & reader to null releases all the system resources and allows the files to be accessed again later
    return data;
}

public void deleteFile(String filePath)
{
    File file;
    try
    {
         file = new File(filePath);
         file.delete();
    }catch(Exception e){e.printStackTrace();}
    file = null;
}

public void createDirectory(String directory)
{
    File directory;
    try
    {
        directory = new File(directory);
        directoyr.mkDir();
    }catch(Exception e){e.printStackTrace();}
    directory = null;
}

希望这有帮助!

答案 1 :(得分:0)

@John Detter,我已经尝试了很大一部分,尽管这是一些好的/有用的代码。

我通过在一个单独的线程中打开文件解析它(当我知道我不是从/向它读/写时)作为RandomAccessFile。我得到了文件的长度,然后调用了raf.skipBytes(length)并删除了文件。 还有其他一些奇怪的东西,但它适用于我。