Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle or Groovy - how to convert URL to file?

Tags:

gradle

groovy

In Gradle I have a file stored on the Internet that I would like to access. But I can't figure out how to convert a URL to a File in Gradle. I need the url to be converted to a file so I can pass it to tasks as a file. Here is what I have so far:

allprojects {
    afterEvaluate { project ->
      String file = new URL('http://techslides.com/demos/samples/sample.json').file
    }
}

this is definetly not what i want. The file variable ends up being: demos/samples/sample.json so it looks like it's just taking the path from the url itself.

I need the actual sample.json to be stored in a File object. I would also prefer if possible to not have to write the file to local storage where it is accessible to other people as its a secure file.

like image 434
j2emanue Avatar asked Dec 25 '16 05:12

j2emanue


People also ask

How do I write a Gradle file?

Writing Build Script. Gradle provides a Domain Specific Language (DSL), for describing builds. This uses the Groovy language to make it easier to describe a build. Each build script of Gradle is encoded using UTF-8, saved offline and named as build.

What is FileTree in Gradle?

A FileTree represents a hierarchy of files. It extends FileCollection to add hierarchy query and manipulation methods. You typically use a FileTree to represent files to copy or the contents of an archive. You can obtain a FileTree instance using Project.

What is Gradle Groovy?

Gradle is a Groovy-based build management system designed specifically for building Java-based projects. Installation instructions can be found here.

What is projectDir in Gradle?

description String The description of the project. projectDir File The directory containing the build script. The value is read-only. buildDir File The directory with the build name in the directory, containing the build script. rootDir File The directory of the project at the root of a project structure.


2 Answers

The simplest way to do this:

def fileLocation = 'file://techslides.com/demos/samples/sample.json'
def fileURL = new URL(fileLocation)
def remoteFile = new File(fileURL.toURI())

See: File(URI uri)

Replace fileLocation with valid value for your task.

like image 91
Andrii Abramov Avatar answered Sep 24 '22 06:09

Andrii Abramov


As of May 4, 2018, Gradle 4.8 RC1 or later, if you are facing this problem using checkstyle, you can use

checkstyle {
    toolVersion = "8.13"
    config project.resources.text.fromUri("${someUrl}/checkstyle.xml")
}

See https://github.com/gradle/gradle/issues/2663

like image 24
Micha Pringle Avatar answered Sep 23 '22 06:09

Micha Pringle