Skip to content

Introduce getContentAsString and getContentAsByteArray to Resource #24651

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@
import java.net.URLConnection;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import org.springframework.util.ResourceUtils;
Expand Down Expand Up @@ -298,6 +301,39 @@ protected void customizeConnection(HttpURLConnection con) throws IOException {
con.setRequestMethod("HEAD");
}

/**
* This implementation returns the contents of a file as a string using the
* system default Charset. Provided the resource exists and the context has
* access to it, the contents will be returned as a single string with line
* feed characters retained.
* @return the contents of the requested file as a {@code String}.
* @throws FileNotFoundException in the event the file path is invalid.
* @throws IOException if the file can not be read or cannot be serialzied.
*/
@Override
public String getContentAsString() throws IOException {

if( !exists() ) {
throw new FileNotFoundException(getDescription() + " cannot be found.");
}
if ( !isReadable() ) {
throw new IOException(getDescription() + " cannot be opened for reading.");
}
return new String(Files.readAllBytes(Paths.get(getFile().getAbsolutePath())), Charset.defaultCharset());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Relying on the default charset is a recipe for disaster, as it can vary between environments and make code fail in collocation that runs fine in another.

Because we cannot determine the resource's charset with a 100% certainty, Resource::getContentAsString() should be removed, or it should be defined to use UTF-8 as default. (see Files::readString)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Poutsma!

As this function is the core of this feature proposal I'll update the request to use utf-8 by default instead of throwing out the whole PR lol.

}

@Override
public String getContentAsString(Charset charset) throws IOException {

if( !exists() ) {
throw new FileNotFoundException(getDescription() + " cannot be found.");
}
if ( !isReadable() ) {
throw new IOException(getDescription() + " cannot be opened for reading.");
}
return new String(Files.readAllBytes(Paths.get(getFile().getAbsolutePath())), charset);

}

/**
* Inner delegate class, avoiding a hard JBoss VFS API dependency at runtime.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@
package org.springframework.core.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;

import org.springframework.lang.Nullable;

Expand Down Expand Up @@ -175,4 +177,41 @@ default ReadableByteChannel readableChannel() throws IOException {
*/
String getDescription();

/**
* Return a {@link ReadableByteChannel}.
* <p>It is expected that each call creates a <i>fresh</i> channel.
* <p>The default implementation returns {@link Channels#newChannel(InputStream)}
* with the result of {@link #getInputStream()}.
* @return the byte channel for the underlying resource (must not be {@code null})
* @throws java.io.FileNotFoundException if the underlying resource doesn't exist
* @throws IOException if the content channel could not be opened
* @since 5.0
* @see #getInputStream()
*/

/**
* Returns the contents of a file as a string using the system default Charset.
* <p>The default implementation returns a {@link Object#toString()} representation of the resource.
* @return the contents of the requested file as a {@code String}.
* @throws FileNotFoundException in the event the file path is invalid.
* @throws IOException if the file can not be read or cannot be accessed.
* @since 5.2.5
*/
default String getContentAsString() throws IOException{
return toString();
}

/**
* Returns the contents of a file as a string using the specified Charset.
* <p>The default implementation returns a {@link Object#toString()} representation of the resource.
* @param charset the {@code Charset} to use to deserialize the content. Defaults to system default.
* @return the contents of the requested file as a {@code String}.
* @throws FileNotFoundException in the event the file path is invalid.
* @throws IOException if the file can not be read or cannot be accessed.
* @since 5.2.5
*/
default String getContentAsString(Charset charset) throws IOException{
return toString();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -337,4 +337,25 @@ void readableChannelNotFoundOnClassPathResource() throws IOException {
new ClassPathResource("Resource.class", getClass()).createRelative("X").readableChannel());
}

@Test
void getContentAsString_givenValidFile_ShouldReturnFileContent() throws IOException {
String expectedString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">\n"
+ "<properties version=\"1.0\">\n"
+ "\t<entry key=\"foo\">bar</entry>\n"
+ "</properties>";

String fileDirString =
new ClassPathResource("org/springframework/core/io/example.xml").getContentAsString();
assertThat(fileDirString).isNotBlank();
assertThat(fileDirString).isEqualTo(expectedString);
}

@Test
void getContentAsString_givenAnInvalidFile_ShouldThrowFileNotFoundException(){
assertThatExceptionOfType(FileNotFoundException.class)
.isThrownBy(new ClassPathResource("nonExistantFile")::getContentAsString);

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties version="1.0">
<entry key="foo">bar</entry>
</properties>

</properties>