I want to convert a text file to a html file and then open it with a browser. I try to use file.renameTo() to rename the text file's extension to .html but the rename attempt always fails and file.renameTo() always returns false. Therefore, when I try to open the file in the below method, the file is opened in notepad.
file declaration:
private File file;
file declaration in constructor:
file = new File("D:/dc1000/Project/webPage.txt");
file.getParentFile().mkdirs();
method that doesn't work:
public void compileWebpage(){
File file2 = new File("D:/dc1000/Project/CompiledWebpage.html");
file2.getParentFile().mkdirs();
addFileTags("end"); //add ending tags like </body>
boolean success = true;
try{
success = file.renameTo(file2);
}catch (Exception e){
System.out.println(e);
}
if(!success){
System.out.println("webPage compilation failed.");
}
Desktop desktop = Desktop.getDesktop();
try{
desktop.browse(file.toURI());
}catch (IOException e){
e.printStackTrace();
}
}
No exceptions are thrown, "Webpage compilation failed" is printed to the console and then notepad opens the file. The file looks like this when opened in notepad:
<html>
<head>
</head>
<body>
<p>hi</p>
</body>
</html>
Why does File.renameTo() always fail? How can I open this text file in a browser as a html file?
Well, off hand it's rather hard to tell without truly knowing what the addFileTag() method is doing. The only reason I can think of is that the webPage.txt file is still open for either read or write operations.
Your code has accessed the file but never closed it again. You can't rename a file that is open. I would have to assume this is in fact done somewhere within the addFileTag() method.
Because your call to the File.renameTo() method was unsuccessful the "webPage.txt" text file was never renamed to "CompiledWebpage.html" so in essence the "CompiledWebpage.html" file simply does not exist within the system. This however is not the reason why the Windows NotePad application is opening your file instead of the expected default Web Browser:
To begin with the File object variable so conveniently named 'file' was declared and initialized to be related to the "D:/dc1000/Project/webPage.txt" text file and it always will be since it's Class global unless of course that relationship is changed somewhere within your code. To be blunt... it's not and I guess it's a good thing for now because IF your File Rename was successful you would have simply gotten an FileNotFound Exception because the text file related to the 'file' variable would no longer exist due to the simple fact that it was renamed.
What you really want to pass to the DeskTop.browse() method is the File object 'file2' variable which is related to the "D:/dc1000/Project/CompiledWebpage.html" text file. Mind you, you'll still get an FileNotFound Exception because the File.renameTo() method had failed. So you definitely want to make sure you have success here.
Whatever...Why did the Windows NotePad application open instead of the Web Browser?
Here's why:
The Operating System File Associations is what determines which application will open the file when using the DeskTop.browse() method. In the Windows Operating System, by default, a file with the file name extension of ".txt" is automatically opened and displayed within NotePad, a file with the file name extension of ".docx" is automatically opened and displayed in MS Office WORD, a file with the file name extension of ".html" is opened and displayed within the default Web Browser. I think you get the idea here.
Because the 'file' variable is still related to the file "D:/dc1000/Project/webPage.txt" and because the File.renameTo() method failed, Windows simply seen the .txt file extension and displayed the file (as stipulated within the 'file' variable) to NotePad.
So...How do I get all this to actually Work!?
Well, if I may be so bold, do this instead:
Place this somewhere in your code, a button action event or whatever:
String sourceFile = "D:/dc1000/Project/webPage.txt";
String destinationFile = "D:/dc1000/Project/CompiledWebpage.html";
boolean success = CompileToWebPage(sourceFile, destinationFile, "This is My Head Text");
if (success) {
System.out.println("Text File Successfully Compiled!");
}
else {
System.out.println("Text File Compilation FAILED!");
}
//Display our new file in the web Browser...
try {
File htmlFile = new File(destinationFile);
Desktop.getDesktop().browse(htmlFile.toURI());
} catch (IOException ex) {}
Here is a new CompileToWebPage() method:
private static boolean CompileToWebPage(final String sourcefilePath,
final String destinationFilePath, String... headText) {
// headText is OPTIONAL.
String headTxt = "";
if (headText.length != 0) { headTxt = headText[0]; }
//Read sourcefilePath file data into a String ArrayList...
BufferedReader input;
try {
input = new BufferedReader(new FileReader(sourcefilePath));
if (!input.ready()) { throw new IOException(); }
}
catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\nThe supplied "
+ "file path was not found!\n\n" + sourcefilePath, "File NotFound",
JOptionPane.ERROR_MESSAGE);
return false;
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\nThe supplied "
+ "file is not ready to be read!\n\n" + ex.getMessage(), "File Not Ready",
JOptionPane.ERROR_MESSAGE);
return false;
}
// Place required HTML Tags into String ArrayList
ArrayList<String> txt = new ArrayList<>();
txt.add("<html>");
txt.add("<head>");
txt.add(headTxt);
txt.add("</head>");
txt.add("<body>");
// Read each line of the source text File and add
// them to our String ArrayList...
try {
String str;
while((str = input.readLine()) != null){
txt.add("<p>" + str + "</p>");
}
input.close();
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\n"
+ "There was a problem reading the source Text from file!\n\n"
+ ex.getMessage(), "File Read Error", JOptionPane.ERROR_MESSAGE);
return false;
}
// Place our HTML finishing Tags into our String ArrayList...
txt.add("</body>");
txt.add("</html>");
// Write the String ArrayList to our supplied Destination
// File Path...
try {
FileWriter fw = new FileWriter(destinationFilePath);
Writer output = new BufferedWriter(fw);
for (int i = 0; i < txt.size(); i++) {
// Some Windows applications (such as NotePad require
// the \r tag for a new line to actually be accomplished
// within a text file.
output.write(txt.get(i) + "\r\n");
}
output.close();
return true;
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\n"
+ "There was a problem writing the Compiled Web Text to file!\n"
+ "Ensure that permissions are properly set.\n\n" + ex.getMessage(),
"File Write Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
Well, I hope this has helped you somewhat or at the very least been entertaining.
Related
I am attempting to display PDFs to the user in their browser using a web service. Once they pass in the URL containing the variables needed. My program first downloads the PDF to local storage then proceeds to copy it to the stream and displays it. Once the viewer is able to view the PDF we wish to delete the file locally so that we do not wind up storing every file searched for. I have managed to accomplish most of this task however I am having issues deleting the file once it is displayed to the user.
Even when I attempt to manually delete the file I receive the "Currently in use in the Java SE Binary" message
Code below:
File testFile = new File("C:\\Users\\stebela\\workspace\\my-app\\invoice"+invNum+".pdf");
try
{
ServletOutputStream os = res.raw().getOutputStream();
FileInputStream inputStr = new FileInputStream(testFile);
IOUtils.copy(inputStr, os);
os.close();
inputStr.close();
//finished settings
res.status(200);
testFile.delete();
} catch (IOException e)
{
System.out.println(e.getMessage());
}
If you don't write to the file, you'r code should work.
If you call inputStr.close(); the file is no longer used by java and it can be deleted.
Pleace check, if your file is not used by any other programm. It's the best if you reboot your PC.
If it still not works, it would be interessting to know, what res is and if your file get's sendet.
I've read this part of the documentation and i think this should solve your problem.
It reads the file into a String and change the header for png images. As the http Body it uses the String of the file.
Make sure, if you change the response type, you have to change the line res.type("image/png"); to the new one.
Here you find the most common ones
File testFile = null;
try {
testFile = new File("C:\\Users\\stebela\\workspace\\my-app\\invoice"+invNum+".png");
FileInputStream fin = new FileInputStream(testFile);
int charAsInt = 0;
String httpBody = "";
while((charAsInt = fin.read()) != -1){
httpBody +=(char)charAsInt;
}
fin.close();
res.body(httpBody);
res.type("image/png");
res.status(200);
testFile.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have to find the original content type(MIME Type) of a file at the time of Uploading.
I want to allow only PDF files, But if i am renaming an .exe fiel to .pdf flie, its type is showing pdf.
I want to restrict these kind of files.
I am using the following code:
if (!fileMultipart.getContentType().equalsIgnoreCase("application/pdf")) {
msg = "Only pdf files are allowed.";
System.out.println("Only pdf files are allowed.");
}
Also some online tools are available to find the original content type. I tried using http://www.checkfiletype.com/ and it works.
The file content type is determined by the user-agent/browser on upload. As you already know, this can be spoofed, or incorrect. There really isn't more you can do with just the file's content type.
An alternative is to do more checking after you have verified the content type by attempting to open the PDF for reading using iText, PDFBox, or some similar library. If you can't open the file then you can let the user know there's a problem with it.
public boolean isPDF(String fileName) {
File file = new File(fileName);
System.out.println("file upload isExist " + file.exists());
boolean result = false;
//Scanner input = null;
try {
Scanner input = new Scanner(new FileReader(file));
System.out.println("fileScanner input " + input);
while (input.hasNextLine()) {
final String checkline = input.nextLine();
if (checkline.contains("%PDF-")) {
// a match!
result = true;
break;
}
}
} catch (FileNotFoundException ex) {
System.out.println("file upload is not valid " + file);
Logger.getLogger(UploadContractorFile.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("file upload final result " + result);
return result;
}
I have this piece of code in my project:
String readFile() {
String pathname = saveDirectory + fileName + ".txt";
String content = "";
File f = new File(pathname);
if (f.exists() && !f.isDirectory()) {
try {
content = new String(Files.readAllBytes(Paths.get(pathname)));
}
catch (IOException e) { }
}
return content;
}
There are no errors, the aplication runs just right, but the content variable never has any text in it and I'm sure that the txt file has text in it!
I've already tried different ways to read the text file (with BufferedReader, Scanner, FileInputStream and FileReader) but none of them worked.
Ps. I'm almost sure that the problem isn't in the pathname variable since I've tried to open the file via code (with Runtime) and it opened the right file normally.
Ok, I tried adding the e.printStackTrace(); but there is still no errors, and it's not missing a / between the directory and the fileName, i've already added in the \\ in the directory variable.
Could you be forgetting the / between the directory and the file name? Print the content of pathname and see.
Or better: debug your code and see what happens.
It looks like you're opening the file once (File f = new File(pathname);), then trying to read it without using the file object you created. You're probably getting an IOException because Files.readAllBytes(Paths.get(pathname)) can't open the file while f has it open.
In my current project I am having an issue with not receiving a file not found exception. My driver file passes the path to be opened to the constructor that is building a library of books. I am using JFileChooser to get the path. In trying to force an error (entering the name of a file that does not exist), it builds the library with no information in it, and does not throw an error.
Driver Code:
//open an existing library
JFileChooser dlg = new JFileChooser ("LibraryData");
FileNameExtensionFilter filter = new FileNameExtensionFilter ("Text Files", "txt");
dlg.setFileFilter(filter);
dlg.setDialogTitle("Select Existing File");
dlg.setApproveButtonToolTipText("Select the file you want to open and click me.");
int button = dlg.showOpenDialog(null);
if (button == dlg.APPROVE_OPTION)
{
currentPath = dlg.getSelectedFile().getPath();
library = new PersonalLibrary(currentPath);
System.out.println("===========================================================");
System.out.println("File opened successfully from: \n" + currentPath);
System.out.println("===========================================================");
}
Util.enterToContinue();
Util.clearScreen();
break;
Library Code:
public PersonalLibrary(String path)
{
try
{
File myFile = new File(path);
if (myFile.exists())
{
Scanner input = new Scanner(myFile);
while(input.hasNext())
{
//code that populates the library
}
input.close();
saveNeeded = false;
}
}
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}
Your checking if the file exists the catch block will never be executed.
if(myFile.exists())
If it doesn't exist nothing else will be executed including catch block. FileNotFoundException could not occur in this block of code. If you want to catch FileNotFoundException get rid of the if block. Or just add an else block and do you processing there whatever processing you want to do when a file doesn't exist.
the method File#exists() checks if a file is existing or not. If it does, it returns true and goes into your if block.
Since the file is not there, it just simply skips the if block and moves on. Since no attempt was made to access a non-existing file object, the exception is not thrown.
If you would like to throw an exception, you have to do so yourself like this,
if(file.exists()) {
//do file operation
} else {
throw new FileNotFoundException("Oops! No file...");
}
I am trying to write some message to text file. The text file is in the server path. I am able to read content from that file. But i am unable to write content to that file. I am getting FileNotFoundException: \wastServer\apps\LogPath\message.txt (Access Denied).
Note: File has a read and write permissions.
But where i am doing wrong. Please find my code below.
Code:
String FilePath = "\\\\wastServer\\apps\\LogPath\\message.txt";
try {
File fo = new File(FilePath);
FileWriter fw=new FileWriter(fo);
BufferedWriter bw=new BufferedWriter(fw);
bw.write("Hello World");
bw.flush();
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please help me on this?
Please check whether you can access the apps and LogPath directory.
Type these on Run (Windows Key + R)
\\\\wastServer\\apps\\
\\\\wastServer\\apps\\LogPath\\
And see whether you can access those directories from the machine and user you are executing the above code.
You don't have write access to the share, one of the directories, or the file itself. Possibly the file is already open.
After this line
File fo = new File(FilePath);
try to print the absolute path
System.out.println( fo.getAbsolutePath() );
And then check whether the file exists in that location, instead of directly checking at
\\\\wastServer\\apps\\LogPath\\message.txt
So , you will know, where the compiler is searching for the file.