0

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

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

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

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

任何提示都会很好

4

2 回答 2

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

希望这有帮助!

于 2011-07-05T18:38:36.800 回答
0

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

我通过在单独的线程中打开文件(当我知道我没有从/向它读取/写入)作为 RandomAccessFile 来解决它。我得到了文件的长度,然后调用了 raf.skipBytes(length) 并删除了文件。还有一些其他奇怪的事情伴随着它,但它对我有用。

于 2011-07-06T20:09:09.720 回答