Error in DownloadLink

I have created a class for Download of Files

public class DownloadLink extends Anchor {

	private static final long serialVersionUID = 1L;

	public DownloadLink(File file) {
		Anchor anchor = new Anchor(getStreamResource(file.getName(), convertFileToString(file)), file.getName());
		anchor.getElement().setAttribute("download", true);
		anchor.setHref(getStreamResource(file.getName(), convertFileToString(file)));
		add(anchor);
	}

	public StreamResource getStreamResource(String filename, String content) {
		return new StreamResource(filename, () -> new ByteArrayInputStream(content.getBytes()));
	}

	private String convertFileToString(File file) {
		StringBuilder fileContents = new StringBuilder((int) file.length());

		try (Scanner scanner = new Scanner(file)) {
			while (scanner.hasNextLine()) {
				fileContents.append(scanner.nextLine() + System.lineSeparator());
			}
			return fileContents.toString();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
}

I can call this class by

File in = new File("C:\\dev\\wcontent\\mail\\attachments\\575\\Demo.txt");
DownloadLink downloadLink = new DownloadLink(in);
add(downloadLink);

This code works well for pure Textfiles.

But it works not for other Files with other Content-Types like pdf, jpg, images, …

Can you help me, that it works also for images, pdf, …

Hi,

Instead of reading your file using a Scanner, can’t you read it using Files.readAllBytes? It will return a byte-array which can be used directly in your ByteArrayInputStream.

I have solved the problem

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import com.vaadin.flow.component.html.Anchor;
import com.vaadin.flow.server.StreamResource;

public class DownloadLink extends Anchor {

	private static final long serialVersionUID = 1L;

	public DownloadLink(File file) {
		Anchor anchor = new Anchor(getStreamResource(file.getName(), file), file.getName());
		anchor.getElement().setAttribute("download", true);
		anchor.setHref(getStreamResource(file.getName(), file));
		add(anchor);
	}

	public StreamResource getStreamResource(String filename, File content) {
		return new StreamResource(filename, () -> {
			try {
				return new ByteArrayInputStream(FileUtils.readFileToByteArray(content));
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		});
	}
}