How to scan a file for viruses in Java
Viruses can be a major problem with user-submitted and sometimes even client-submitted content. The best way to keep your system safe is to screen all incoming files before they can even interact with it. To accomplish this, this tutorial will lay out how to quickly and easily set up an automatic virus scanning system using Java. Let’s get straight to it.
First we need to use Jitpack to dynamically compile our library. Toward this end, we need to add references for our repository and depository to the Maven POM file:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
And:
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v2.75</version>
</dependency>
</dependencies>
Now we simply call scanFile:
// Import classes://import com.cloudmersive.client.invoker.ApiClient;//import com.cloudmersive.client.invoker.ApiException;//import com.cloudmersive.client.invoker.Configuration;//import com.cloudmersive.client.invoker.auth.*;//import com.cloudmersive.client.ScanApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: ApikeyApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");Apikey.setApiKey("YOUR API KEY");// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.setApiKeyPrefix("Token");ScanApi apiInstance = new ScanApi();File inputFile = new File("/path/to/file"); // File | Input file to perform the operation on.try {VirusScanResult result = apiInstance.scanFile(inputFile);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling ScanApi#scanFile");e.printStackTrace();}
And that’s it! Our response will be given in this format:
{
"CleanResult": true,
"FoundViruses": [
{
"FileName": "string",
"VirusName": "string"
}
]
}
Our virus scanning supports over 17 million virus definitions and receives cloud based updates constantly. If you need a higher degree of customization, you can also use the scanFileAdvanced function, which allows you to fine tune your criteria, letting you block executable files, scripts, and invalid files.