I have a PDF in project location how to open pdf file
my project name is MyProject
My pdf is under project folder
MyProject\Pdf\test.pdf how to open my pdf file
I need to open pdf file in the project location
I have tried below code
final Button viewBtn= new Button("View Policy Schedule");
viewBtn.addClickListener( newButton.ClickListener() public void buttonClick(ClickEvent event) {
Window window = new Window();
window.setResizable(true);
window.setCaption("Claim Form Covering Letter PDF");
window.setWidth("800");
window.setHeight("600");
window.setModal(true);
window.center();
final String filepath = "Pdf//test.pdf";
File f = new File(filepath);
System.out.println(f.getAbsolutePath());
Path p = Paths.get(filepath);
String fileName = p.getFileName().toString();
StreamResource.StreamSource s = new StreamResource.StreamSource() {
/**
*
*/
private static final long serialVersionUID = 9138325634649289303L;
public InputStream getStream() {
try {
File f = new File(".");
System.out.println(f.getCanonicalPath());
FileInputStream fis = new FileInputStream(f);
return fis;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
};
StreamResource r = new StreamResource(s, fileName);
Embedded e = new Embedded();
e.setSizeFull();
e.setType(Embedded.TYPE_BROWSER);
r.setMIMEType("application/pdf");
e.setSource(r);
window.setContent(e);
UI.getCurrent().addWindow(window);
}
});
It's not working I have got a file not found exception
Move the PDF so you can read it from the classpath. If you are using Maven put it in src/main/resources. Otherwise put it in some package.
You can then read it using getResourcesAsStream() method of java.lang.class.
InputStream in = this.getClass().getResourcesAsStream("/test.pdf"); //classpath root
InputStream in = this.getClass().getResourcesAsStream("/my/package/name/test.pdf"); //from some package
Updated
final Button viewBtn= new Button("View Policy Schedule");
viewBtn.addClickListener( newButton.ClickListener()
public void buttonClick(ClickEvent event) {
Window window = new Window();
window.setResizable(true);
window.setCaption("Claim Form Covering Letter PDF");
window.setWidth("800");
window.setHeight("600");
window.setModal(true);
window.center();
StreamResource.StreamSource s = new StreamResource.StreamSource() {
public InputStream getStream() {
try {
return this.getClass().getResourcesAsStream("/test.pdf");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
};
StreamResource r = new StreamResource(s, fileName);
Embedded e = new Embedded();
e.setSizeFull();
e.setType(Embedded.TYPE_BROWSER);
r.setMIMEType("application/pdf");
e.setSource(r);
window.setContent(e);
UI.getCurrent().addWindow(window);
}
});
Related
I am new to Java and I have a project to do, so I have a java file and the user have to choose from a listing of files in a directory. The input from user is saved in a variable (fileName). I want to use that variable in another java file for doing some other work. I searched online but didn't find any solution that works for me. Probably I've done something wrong.
code of the first file:
public class Director {
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
public static void main(String[] args) throws IOException {
// Creates an array in which we will store the names of files and directories
String[] pathnames;
// Creates a new File instance by converting the given pathname string
// into an abstract pathname
File f = new File("C:\\Users\\miltos\\Desktop\\polimesa\\available_videos");
// Populates the array with names of files and directories
pathnames = f.list();
System.out.println("Files in the directory:");
// For each pathname in the pathnames array
for (String pathname : pathnames) {
// Print the names of files and directories
System.out.println(pathname);
}
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter file name");
String fileName = myObj.nextLine();
File source = new File("C:\\Users\\miltos\\Desktop\\polimesa\\available_videos\\" + fileName);
File dest = new File("C:\\Users\\miltos\\Desktop\\polimesa\\raw_videos\\" + fileName);
copyFileUsingStream(source, dest);
}
}
code of the second file that i want to use the input:
public class TestFFMpeg {
static Logger log = LogManager.getLogger(TestFFMpeg.class);
public static void main(String[] args) {
FFmpeg ffmpeg = null;
FFprobe ffprobe = null;
try {
log.debug("Initialising FFMpegClient");
ffmpeg = new FFmpeg("C:\\Users\\miltos\\ffmpeg\\bin\\ffmpeg.exe");
ffprobe = new FFprobe("C:\\Users\\miltos\\ffmpeg\\bin\\ffprobe.exe");
} catch (IOException e) {
e.printStackTrace();
}
log.debug("Creating the transcoding");
FFmpegBuilder builder = new FFmpegBuilder()
.setInput("C:\\Users\\miltos\\Desktop\\polimesa\\raw_videos\\" + filename) //updated
.addOutput("C:\\Users\\miltos\\Desktop\\polimesa\\videos\\" + filename) //updated
.setVideoBitRate(200000)
.done();
log.debug("Creating the executor");
FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe);
log.debug("Starting the transcoding");
// Run a one-pass encode
executor.createJob(builder).run();
log.debug("Transcoding finished");
}
}
I created a variable names filename in class second also, which you will pass from the class one , while creating an object of class second like
TestFFMpeg obj = new TestFFMpeg();
obj.methodInSecondClass(filename);
Second Class :
public class TestFFMpeg {
static Logger log = LogManager.getLogger(TestFFMpeg.class);
public void methodInSecondClass(String filename){
FFmpeg ffmpeg = null;
FFprobe ffprobe = null;
try {
log.debug("Initialising FFMpegClient");
ffmpeg = new FFmpeg("C:\\Users\\miltos\\ffmpeg\\bin\\ffmpeg.exe");
ffprobe = new FFprobe("C:\\Users\\miltos\\ffmpeg\\bin\\ffprobe.exe");
} catch (IOException e) {
e.printStackTrace();
}
log.debug("Creating the transcoding");
FFmpegBuilder builder = new FFmpegBuilder()
.setInput("C:\\Users\\miltos\\Desktop\\polimesa\\available_videos\\"+filename) //this is where i want the same variable
.addOutput("C:\\Users\\miltos\\Desktop\\polimesa\\videos\\"+filename) //this is where i want the same variable
.setVideoBitRate(200000)
.done();
log.debug("Creating the executor");
FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe);
log.debug("Starting the transcoding");
// Run a one-pass encode
executor.createJob(builder).run();
log.debug("Transcoding finished");
}
}
I'm trying to play a song from a folder that a user selects. Essentially, I am using my own Queue that I've created and I'm getting the right path.
Within the code below, I am using a Var called path. The path is "C:\Users\Shaun\Downloads\TestMusic\Ed Sheeran - Shape of You.mp3". When I define the path as just, "Ed Sheeran - Shape of You.mp3". It works! This tells me that this looks into the directory of where the project is started or runned from.
So, how do I make it play a file from any given directory?
The 'path' I'm referring to is below, " public void handlecentreButtonClick()".
public class graphicalController implements Initializable
{
//GUI Decleration
public Button centreButton;
public Button backButton;
public Button forwardButton;
public ToggleButton muteToggle;
public MenuItem loadFolder;
//Controller Decleration
String absolutePath;
SongQueue q = new SongQueue();
MediaPlayer player;
#Override
public void initialize(URL location, ResourceBundle resources)
{
centreButton.setStyle("-fx-background-image: url('/Resources/Play_Button.png')");
centreButton.setText("");
backButton.setStyle("-fx-background-image: url('/Resources/Back_Button.png')");
backButton.setText("");
forwardButton.setStyle("-fx-background-image: url('/Resources/Forward_Button.png')");
forwardButton.setText("");
muteToggle.setStyle("-fx-background-image: url('/Resources/ToggleSound_Button.png')");
muteToggle.setText("");
}
public void handlecentreButtonClick() {
if(!(q.isEmpty())) {
String file = q.peek().fileName.toString();
String path = absolutePath + "\\" + file;
Media song = new Media(path);
player = new MediaPlayer(song);
player.play();
}
}
public void handleforwardButtonClick() {
System.out.println("Hello.");
centreButton.setText("Hello");
}
public void handlebackButtonClick() {
System.out.println("Hello.");
centreButton.setText("Hello");
}
public void handleLoadButtonClick() {
DirectoryChooser directoryChooser = new DirectoryChooser();
File selectedDirectory = directoryChooser.showDialog(null);
absolutePath = selectedDirectory.getAbsolutePath();
String path = absolutePath;
loadFilesFromFolder(path);
}
public void loadFilesFromFolder(String path) {
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
while(!(q.isEmpty()))
{
try {Thread.sleep(500);}catch (Exception e){}
Song j = q.pop();
}
int listLength = listOfFiles.length;
for (int k = 0; k < listLength; k++) {
if (listOfFiles[k].isFile()) {
String fileName = listOfFiles[k].getName();
String fileNamePath = path + "\\" +fileName;
try {
InputStream input = new FileInputStream(new File(fileNamePath));
ContentHandler handler = new DefaultHandler();
Metadata metadata = new Metadata();
Parser parser = new Mp3Parser();
ParseContext parseCtx = new ParseContext();
parser.parse(input, handler, metadata, parseCtx);
input.close();
String songName = metadata.get("title");
String artistName = metadata.get("xmpDM:artist");
String albumName = metadata.get("xmpDM:genre");
int id = k + 1;
Song newSong = new Song(id, fileName, songName, artistName, albumName);
q.push(newSong);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
}
}
}
}
Use
Media song = new Media(new File(path).toURI().toString());
I strongly recommend you construct the file in a platform independent way, however, instead of hard-coding a file separator specific to one particular file system. You can do
File path = new File(absolutePath, file);
Media song = new Media(path.toURI().toString());
With the help of #James_D...
You Cannot:
Media song = new Media("C:\Users\Shaun\Downloads\TestMusic\Ed Sheeran - Shape of You.mp3");
This will try and find the directory from the point of where you've launched your program.
Do:
Media song = new Media(new File(path).toURI().toString());
I searched around but couldn't find nothing on this.
I would like to set the save (destination) path for a file selected in Filechooser. For example, I selected a picture called 'test.jpg', I would like for this 'test.jpg' to be saved to C:\blah\blah\blah\Pictures. How can I pull this off?
So far the code I have
public void OnImageAddBeer(ActionEvent event){
FileChooser fc = new FileChooser();
//Set extension filter
fc.getExtensionFilters().addAll(new ExtensionFilter("JPEG Files (*.jpg)", "*.jpg"));
File selectedFile = fc.showOpenDialog(null);
if( selectedFile != null){
}
}
All you need to do is copy the content inside the file choose in wherever you want, try something like this:
if(selectedFile != null){
copy(selectedFile.getAbsolutePath(), "C:\\blah\\blah\\blah\\Pictures\\test.jpg");
}
and the method copy:
public void copy(String from, String to) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(from);
fw = new FileWriter(to);
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
//...
}
}
Basically copy just copy the content of the file located in from inside a new file located at to.
Try this:
String fileName = selectedFile.getName();
Path target = Paths.get("c:/user/test", fileName);
Files.copy(selectedFile.toPath(), target);
Add this statement if you want to set the destination path:
fc.setInitialDirectory(new File(System.getProperty("user.home") + "\\Pictures"));
Take this:
String dir = System.getProperty("user.dir");
File f = new File(dir + "/abc/def");
fc.setInitialDirectory(f);
I'm looking for a solution to create reports using JasperReports for my application. I found some examples but still could not make it work. I'm using Vaadin7
I'm trying this
public class Report {
public Report(){
createShowReport();
}
private void createShowReport(){
final Map map = new HashMap();
StreamResource.StreamSource source = new StreamResource.StreamSource() {
public InputStream getStream() {
byte[] b = null;
try {
b = JasperRunManager.runReportToPdf(getClass().getClassLoader().getResourceAsStream("br/ind/ibg/reports/report3.jasper"), map, new JREmptyDataSource());
} catch (JRException ex) {
ex.printStackTrace();
}
return new ByteArrayInputStream(b);
}
};
StreamResource resource = new StreamResource(source, "report3.pdf");
resource.setMIMEType("application/pdf");
VerticalLayout v = new VerticalLayout();
Embedded e = new Embedded("", resource);
e.setSizeFull();
e.setType(Embedded.TYPE_BROWSER);
v.addComponent(e);
Window w = getWindow();
w.setContent(v);
UI.getCurrent().addWindow(w);
}
private Window getWindow(){
Window w = new Window();
w.setSizeFull();
w.center();
return w;
}
}
Any idea ?
Problem seems to be on the JasperPrint printer = JasperFillManager.fillReport(file, parametros,dados); line.
Make sure that your report is found (file is not null).
In order to show the report, what I usually do is put the resulted pdf in a stream, then create a streamResource with mimeType='application\pdf' and use window.open(resource) to show it.
Example:
StreamResource.StreamSource source = new StreamResource.StreamSource() {
public InputStream getStream() {
byte[] b = null;
try {
b = JasperRunManager.runReportToPdf(getClass().getClassLoader().getResourceAsStream("reports/report3.jasper"), map, con);
} catch (JRException ex) {
ex.printStackTrace();
}
return new ByteArrayInputStream(b);
}
};
StreamResource resource = new StreamResource(source, "report3.pdf", getApplication());
resource.setMIMEType("application/pdf");
getApplication().getMainWindow().open(resource, "_new");
In my Flex Application i'm doing image Uploading Using Blazeds ...
private var fileReference:FileReference;
protected function imageUpload(event:MouseEvent):void
{
// create a fileFilter - class declaration
var imageTypes:FileFilter;
// set the file filter type - jpg/png/gif - init method
imageTypes = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
fileReference = new FileReference();
fileReference.browse([imageTypes]);
fileReference.addEventListener(Event.SELECT, browseImage);
fileReference.addEventListener(Event.COMPLETE, uploadImage);
}
private function browseImage(event:Event):void {
fileReference.load();
}
private function uploadImage(event:Event):void {
profileImage.source = fileReference.data;
var name:String = fileReference.name;
var directory:String = "/EClassV1/flex_src/Images";
var content:ByteArray = new ByteArray();
fileReference.data.readBytes(content, 0, fileReference.data.length);
var fileAsyn:AsyncToken = userService.uploadImage(name,directory,content);
fileAsyn.addResponder(new mx.rpc.Responder(handler_success, handler_failure));
}
And in my Java Code...
#RemotingInclude
public void uploadImage(String name, String directory, byte[] content) {
File file = new File(directory);
if (!file.exists()) {
file.mkdir();
}
name = directory + "/" + name;
File fileToUpload = new File(name);
try {
FileOutputStream fos = new FileOutputStream(fileToUpload);
fos.write(content);
System.out.println("file write successfully");
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
But it giving... error..
java.io.FileNotFoundException: \EClassV1\flex_src\Images\image001.png (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
Actually i want to Sore file into folder and store Database..
Help me..
You need to create the file if it does not exist yet. The method createNewFile() will do this for you:
File fileToUpload = new File(name);
fileToUpload.createNewFile();
try {
FileOutputStream oFile = new FileOutputStream(fileToUpload, false);
...