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:




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.

Written by

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store