File is used by another process java

Java Cannot delete file, being used by another process

I want to delete the file ‘SHA1.txt’. How can I do this?

Best Solution

I guess with sameSha1 you open SHA1.txt to read it and you forget to close it.

From your comment you contain the following line in sameSha1 :

String sha1Txt = new Scanner(new File("SHA1.txt")).useDelimiter("\\Z").next(); 

So you create a scanner instance but you don’t explicitly close it. You should do something like that:

Scanner s = new Scanner(new File("SHA1.txt")); try < String sha1Txt = s.useDelimiter("\\Z").next(); . return result; >finally

Or as @HuStmpHrrr suggests in Java 7:

try(Scanner s = new Scanner(new File("SHA1.txt")))
Java – How to call one constructor from another in Java
public class Foo < private int x; public Foo() < this(1); >public Foo(int x) < this.x = x; >> 

To chain to a particular superclass constructor instead of one in the same class, use super instead of this . Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.

See also this related question, which is about C# but where the same principles apply.

Java – How to create a Java string from the contents of a file

Read all text from a file

Java 11 added the readString() method to read small files as a String , preserving line terminators:

String content = Files.readString(path, StandardCharsets.US_ASCII); 

For versions between Java 7 and 11, here’s a compact, robust idiom, wrapped up in a utility method:

static String readFile(String path, Charset encoding) throws IOException

Read lines of text from a file

Java 7 added a convenience method to read a file as lines of text, represented as a List . This approach is «lossy» because the line separators are stripped from the end of each line.

List lines = Files.readAllLines(Paths.get(path), encoding); 

Java 8 added the Files.lines() method to produce a Stream . Again, this method is lossy because line separators are stripped. If an IOException is encountered while reading the file, it is wrapped in an UncheckedIOException , since Stream doesn’t accept lambdas that throw checked exceptions.

try (Stream lines = Files.lines(path, encoding))

This Stream does need a close() call; this is poorly documented on the API, and I suspect many people don’t even notice Stream has a close() method. Be sure to use an ARM-block as shown.

If you are working with a source other than a file, you can use the lines() method in BufferedReader instead.

Memory utilization

The first method, that preserves line breaks, can temporarily require memory several times the size of the file, because for a short time the raw file contents (a byte array), and the decoded characters (each of which is 16 bits even if encoded as 8 bits in the file) reside in memory at once. It is safest to apply to files that you know to be small relative to the available memory.

Читайте также:  Javascript выбрать первую строку

The second method, reading lines, is usually more memory efficient, because the input byte buffer for decoding doesn’t need to contain the entire file. However, it’s still not suitable for files that are very large relative to available memory.

For reading large files, you need a different design for your program, one that reads a chunk of text from a stream, processes it, and then moves on to the next, reusing the same fixed-sized memory block. Here, «large» depends on the computer specs. Nowadays, this threshold might be many gigabytes of RAM. The third method, using a Stream is one way to do this, if your input «records» happen to be individual lines. (Using the readLine() method of BufferedReader is the procedural equivalent to this approach.)

Character encoding

One thing that is missing from the sample in the original post is the character encoding. There are some special cases where the platform default is what you want, but they are rare, and you should be able justify your choice.

The StandardCharsets class defines some constants for the encodings required of all Java runtimes:

String content = readFile("test.txt", StandardCharsets.UTF_8); 

The platform default is available from the Charset class itself:

String content = readFile("test.txt", Charset.defaultCharset()); 

Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the «edited» link on this answer.

Related Question

Источник

Process cannot access file because it is being used by another process

Solution 1: The destinaton Directory of the zipped file: is included in the path of the source Directory, the base Directory of the compression operation: . ZipFile.CreateFromDirectory includes the SubDirectories tree structure of the base Directory and it’s content when creating the compressed file, hence it tries to also compress the destination File that it’s creating. The User Temp Directory is returned by Environment.GetEnvironmentVariable(): You also need to delete the Temp zip file and, in any case, verify that it doesn’t already exist (a file with that name could be there for any reason and trying to overwrite it will cause an error).

Process cannot access file because it is being used by another process

I solved this problem using two threads Producer and Consumer . One thread which was generating the data to write in the file was putting those data objects to LinkedBlockingQueue and another thread was fetching data from this queue using take () method and persisting data objects into the file.

Advantage of using LinkedBlockingQueue over others is that it provides take () method which retrieves and removes the head of this queue waiting if necessary until an element becomes available and put() method which waits until necessary space is available.

Читайте также:  Соседние селекторы

Java — process cannot access file because it is being, Files.write is opening the, writing the data and then closing, so in you example code, that’s two open/close operations in that block alone. You might consider using a producer/consumer approach to buffer the output and take manual control over the opening/closing of the file. For example, while there is …

The process cannot access the file because it is being used by another process. Unexpected error

Changing the looping, as suggested in the comments, will not result if the file is locked. For sure your app is locking the file. This can mean that you are trying to upload the file before ts is released by the third party, or before the writing to it is finished (this can happen with buffered IO).

If you don’t have access to the third party app to check what it is doing (and change it if necessary), you can do something like this:

This first routine checks if the file is locked (taken from here: Is there a way to check if a file is in use?

//routine to check if the file is locked protected virtual bool IsFileLocked(FileInfo file) < FileStream stream = null; try < stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); >catch (IOException) < //the file is unavailable because it is: //still being written to //or being processed by another thread //or does not exist (has already been processed) return true; >finally < if (stream != null) stream.Close(); >//file is not locked return false; > public void SendFile(string filename, int maxTries) < bool done; while(true) < if(condition == true) < if(!IsFileLocked(filename)) < Process[] processes = Process.GetProcessByName("ThirdPartyApp"); foreach (var proc in processes) proc.Kill(); using (System.Net.WebClient client = new System.Net.WebClient()) < client.Credentials = new System.Net.NetworkCredential("username", "password"); int count = 0; done = false; while (count < maxTries || !done) < try < client.UploadFile(ftpServer + new FileInfo(filename).Name, "STOR", filename); done = true; >catch(Exception ex) < System.Threading.Thread.Sleep(5000); count++; >> if (!done) < //handle the error >> File.Delete(filename); Process.Start("ThirdPartyApp"); > > > > 

If it is a problem of a temporary locker, this can help you to solve it. But be warned that if you kill the third party before it releases the file, and the File.Exist can give you the false impression that the process finished it’s job, you will still get a lock in the file.

Another point is the the Check to see if the file is locked can also fail, if just after the check the «ThirdPartyApp» locks the file and you kill the app before the app releases it.

So, to me the best answer is to use thsi code and try to open the file (locking it yourself). If this is possible (no exception), send to FTP using the opened stream.After finish, close it, delete the file and run the ThirdApp again.

EDIT: Add code to see if the file is locked and only if not delete the ThirdPartyApp and after this to execute the rest of the code.

«The process cannot access the file because it is being, The process cannot access the file because it is being used by another process. Again I have no clue how am I going to somehow close the process. c# asp.net file-in-use. Share. which I have done in my example above. You were concatenating the newPath over and over again. Share. Usage exampleFile.WriteAllBytes(newPath, item.File);Feedback

Читайте также:  Java float количество знаков после запятой

A process cannot access a File because it is being used by another process

The destinaton Directory of the zipped file:
@»C:\temp\logfiles\[Some Name]\Zip»

is included in the path of the source Directory, the base Directory of the compression operation:
@»C:\temp\logfiles\[Some Name] .

ZipFile.CreateFromDirectory includes the SubDirectories tree structure of the base Directory and it’s content when creating the compressed file, hence it tries to also compress the destination File that it’s creating. Of course it can’t access it, because it’s (guess what) in use.

If you move the destination Directory outside the base Path, it won’t raise any exception.

You could use the User Temp directory as a temporary destination for the zipped file and then move it to the destination Directory when it’s complete.

The User Temp Directory is returned by Environment.GetEnvironmentVariable():

Environment.GetEnvironmentVariable("Temp", EnvironmentVariableTarget.User); 

You also need to delete the Temp zip file and, in any case, verify that it doesn’t already exist (a file with that name could be there for any reason and trying to overwrite it will cause an error).

An example of a possible method to create a ZipFile using the User Temp Directory:

string SourceFolder = @"C:\temp\logfiles\"; string DestinationFolder = @"C:\temp\logfiles\Zip"; string ZippedFileName = "ZippedFile.zip"; string UserTempFolder = Environment.GetEnvironmentVariable("Temp", EnvironmentVariableTarget.User); string ZippedTempFile = Path.Combine(UserTempFolder, ZippedFileName); if (File.Exists(ZippedTempFile)) < File.Delete(ZippedTempFile); >ZipFile.CreateFromDirectory(SourceFolder, ZippedTempFile); Directory.CreateDirectory(DestinationFolder); File.Move(ZippedTempFile, Path.Combine(DestinationFolder, ZippedFileName)); 

This happens most often* if you do not dispose of the FileHandle (or whatever encapsualtes said handle). File Handles and Network connections are the prime examples of Unmanaged resoruce that need Disposing. You should always dispose them.

I always consider it a bad idea to split up the creation and diposing of any disposeable resource. You should always do Create, Use and Dispose in the same piece of code (like inside that Button click). Ideally do so with a using-block. Advanced programemrs can ignore that, but based on your problem I think you are more on teh beginner side.

*Aside from the file being plain open in another Programm, of course!

File being used by another process, cannot be accessed, The process cannot be accessed because it’s being used by another process 233 IOException: The process cannot access the file ‘file path’ because it is being used by another process

The process cannot access the file because it is being used by another process: ‘keylog.txt’

Try open/close the file for every log line?

import time def on_press(key): with open('keylog.txt', 'a') as logfile: now = time.asctime() log_line = '<> - <>\n'.format(now, str(key)) logfile.write(log_line) 

The process cannot access the file because it is being, Not necessarily. There are a number of reasons for this to happen. For example: at the first time, the file is already there, because the ThirdPartApp was already running and had finish it’s job when your app starts, and the second time, it is processing the file when you simply kill it. Getting «The process …

Источник

Оцените статью