FileInputStream FileNotFoundException but file definitely exists - java

I am encountering a weird FileNotFoundException with FileInputStream while working in Android Studio. Using this post, I ran some checks, but still cannot find the issue.
This is my code:
package com.mypackage;
import java.io.FileInputStream;
import java.sql.*;
import java.util.*;
import java.util.logging.Logger;
import java.io.File;
public class DatabaseDriver {
public DatabaseDriver(){
Properties properties = new Properties();
// get credentials from application.properties file
FileInputStream in = new FileInputStream("application.properties");
properties.load(in);
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
}
}
With some of the tips from the above post, I ran the following code in a debugging attempt:
public class DatabaseDriver {
public DatabaseDriver(){
File file = new File("application.properties");
System.out.println(new File(".").getAbsolutePath());
System.out.println(new File("application.properties").getAbsolutePath());
System.out.println(file.exists());
System.out.println(file.canRead());
System.out.println(file.isDirectory());
}
}
And the output when I create a DatabaseDriver instance in a main:
C:\Users\erin\AndroidStudioProjects\RecCenter\.
C:\Users\erin\AndroidStudioProjects\RecCenter\application.properties
true
true
false
That all seems fine, so I'm a little lost.

Related

What Does "file does not contain class api.configuration" Mean?

Please keep in mind that I am completely new to Java. I don't know what 'classes' and stuff are.
When trying to compile (javac -g Sphinx.java) this code:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import api.Configuration;
import api.SpeechResult;
import api.LiveSpeechRecognizer;
public class Sphinx {
public static void main(String[] args) throws Exception {
Configuration configuration = new Configuration();
configuration.setAcousticModelPath("models/en-us/en-us");
configuration.setDictionaryPath("models/en-us/cmudict-en-us.dict");
configuration.setLanguageModelPath("models/en-us/en-us.lm.bin");
PrintWriter pw = new PrintWriter(new PrintWriter("status.txt"));
LiveSpeechRecognizer recognizer = new LiveSpeechRecognizer(configuration);
recognizer.startRecognition(true);
pw.print("running");
SpeechResult result = recognizer.getResult();
recognizer.stopRecognition();
pw.print("stopped");
pw.close();
PrintWriter pw2 = new PrintWriter(new PrintWriter("result.txt"));
pw2.println(result);
pw2.close();
}
}
I get this error:
Sphinx.java:8: error: cannot access Configuration
import api.Configuration;
^
bad source file: .\api\Configuration.java
file does not contain class api.Configuration
Please remove or make sure it appears in the correct subdirectory of the sourcepath.
I don't quite understand what 'file does not contain class api.configuration' means, or how to fix it.
Looking at your error message, it seems like your ./api/Configuration.java file is missing a package declaration.
Can you make sure that in ./api/Configuration.java the first line has
package api;
This tells the compiler that your file is accessible through the api package, not the default package.

Convert File object to URI object where the path contains spaces

In my program I have the conversion as illustrated by the test.
Path->File->URI->URL->File.
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
#RunWith(JUnit4.class)
public class UrlStuffTest {
#Test
public void testFileToUriToUrlWithCreateFile() throws MalformedURLException, IOException {
Path p = Paths.get("testfolder", "xmls");
File f = p.toAbsolutePath().toFile();
f.mkdirs();
System.out.println(f);
URI uri = f.toURI();
System.out.println(uri);
URL url = uri.toURL();
System.out.println(url);
File aXmlFile = new File(url.getPath(), "test.xml");
System.out.println(aXmlFile);
aXmlFile.createNewFile();
}
#Test
public void testFileToUriToUrlWithCreateFileAndSpaceInPath() throws MalformedURLException, IOException {
Path p = Paths.get("test folder", "xmls");
File f = p.toAbsolutePath().toFile();
f.mkdirs();
System.out.println(f);
URI uri = f.toURI();
System.out.println(uri);
URL url = uri.toURL();
System.out.println(url);
File aXmlFile = new File(url.getPath(), "test.xml");
System.out.println(aXmlFile);
aXmlFile.createNewFile();
}
}
If you run the methods you will see that the upper one succeeds. The last one has a space in the path and fails on the last line basically saying "System can not find path...".
Output of the first method is
C:\Development\Workspace\spielwiese\testfolder\xmls
file:/C:/Development/Workspace/spielwiese/testfolder/xmls/
file:/C:/Development/Workspace/spielwiese/testfolder/xmls/
C:\Development\Workspace\spielwiese\testfolder\xmls\test.xml
Output of the second method is
C:\Development\Workspace\spielwiese\test folder\xmls
file:/C:/Development/Workspace/spielwiese/test%20folder/xmls/
file:/C:/Development/Workspace/spielwiese/test%20folder/xmls/
C:\Development\Workspace\spielwiese\test%20folder\xmls\test.xml
So when converting from File to URI the space becomes a %20. I guess this is what makes the final XML file creation fail.
I solved this issue in my program by skipping the conversion from File to URI by using File.toURL() method. This method is deprecated though.
What would be a better solution?
You need to decode the URL string before using it as File path. Something like this
String decodedUrlPath = java.net.URLDecoder.decode(url.getPath(), StandardCharsets.UTF_8.name());
Really weird. With Path-File and without URL/URI it runs fine. Was trying to find other hints, but stuck on this one also:
Path path = Paths.get("test folder\\xmls", "test1.xml");
File aXmlFile = path.toFile();
System.out.println(aXmlFile);
aXmlFile.createNewFile();
So I guess in your URI you have to replace %20 pack to spaces " ".
That code works:
aXmlFile = new File(url.getPath().replaceAll("%20", " "), "test.xml");
System.out.println(aXmlFile);
aXmlFile.createNewFile();

Nullpointer Exception While Using Trying to Read Excel in Selenium

Hi guys i Searched Every Where Solution For But Can't Find. Why Am Getting Null Pointer Exception For This i Dunno. Please Sort Me This Out. It is Showing as Path is Only Wrong But i Specified it Correctly only.
My Code :
package UsingExcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.sun.rowset.internal.Row;
public class Demo
{
public void ReadExcel(String filepath,String filename,String Sheetname) throws IOException
{
File file = new File(filepath); // line 21
FileInputStream stream = new FileInputStream(file);
Workbook Mybook = null;
String FileExtensionnname = filename.substring(filename.indexOf("."));
if(FileExtensionnname.equals(".xlsx"))
{
Mybook = new XSSFWorkbook(stream);
}
else if(FileExtensionnname.equals(".xls"))
{
Mybook = new HSSFWorkbook(stream);
}
Sheet filesheet = Mybook.getSheet(Sheetname);
int rowcount = filesheet.getLastRowNum()-filesheet.getFirstRowNum();
for(int i=0;i<rowcount+1;i++)
{
org.apache.poi.ss.usermodel.Row row =filesheet.getRow(i);
for(int j=0;j<row.getLastCellNum();j++)
{
System.out.println(row.getCell(j).getStringCellValue()+ "||");
}
System.out.println();
}
}
public static void main(String[] args) throws IOException
{
Demo excelfile = new Demo();
String filepath = System.getProperty("E:\\Mybook.xlsx");
excelfile.ReadExcel(filepath, "Mybook.xlsx", "DemoExcel");
}
}
My Error is :
Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(Unknown Source)
at UsingExcel.Demo.ReadExcel(Demo.java:21)
at UsingExcel.Demo.main(Demo.java:61)
Hope You Have Understood My Problem, Please Sort This out. But When am Testing a Login Page Using Excel That No Problem Will Be Coming, Now i Try To Print on The
Console it is Not Working.
Your filepath should just be
String filepath = "E:\\Mybook.xlsx", don't use System.getProperty.
From docs :
Gets the system property indicated by the specified key
A null is being passed to your method ReadExcel(...), because there is no System property defined as E:\Mybook.xlsx

How to convert HTML To PDF and open pdf file, using java with YaHP Html to Pdf Convertor

Am using a YaHP-Converter to convert HTML File to Pdf. Here is the code example i have used for converting. The code works me fine. But i want open Pdf file after this conversion.
Any idea please.
CYaHPConverter converter = new CYaHPConverter();
FileOutputStream out = new FileOutputStream(pdfOut);
Map properties = new HashMap();
List headerFooterList = new ArrayList();
properties.put(IHtmlToPdfTransformer.PDF_RENDERER_CLASS,IHtmlToPdfTransformer.FLYINGSAUCER_PDF_RENDERER);
converter.convertToPdf(htmlContents,
IHtmlToPdfTransformer.LEGALL,
headerFooterList,
"file:///D:/temp/",
out,
properties);
Thanks in advance
I think this helps:
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
// http://www.allcolor.org/YaHPConverter/
import org.allcolor.yahp.converter.CYaHPConverter;
import org.allcolor.yahp.converter.IHtmlToPdfTransformer;
public class HtmlToPdf_yahp_2 {
public static void main(String ... args ) throws Exception {
String root = "c:/temp/html";
String input = "file_1659686.htm"; // need to be charset utf-8
htmlToPdfFile(new File(root, input),
new File(root, input + ".pdf"));
System.out.println("Done");
}
public static void htmlToPdfFile(File htmlIn, File pdfOut) throws Exception {
Scanner scanner =
new Scanner(htmlIn).useDelimiter("\\Z");
String htmlContents = scanner.next();
CYaHPConverter converter = new CYaHPConverter();
FileOutputStream out = new FileOutputStream(pdfOut);
Map properties = new HashMap();
List headerFooterList = new ArrayList();
properties.put(IHtmlToPdfTransformer.PDF_RENDERER_CLASS,
IHtmlToPdfTransformer.FLYINGSAUCER_PDF_RENDERER);
//properties.put(IHtmlToPdfTransformer.FOP_TTF_FONT_PATH, fontPath);
converter.convertToPdf(htmlContents,
IHtmlToPdfTransformer.A4P,
headerFooterList,
"file:///temp/html/",
out,
properties);
out.flush();
out.close();
}
}
See this for futher info:
http://www.rgagnon.com/javadetails/java-convert-html-to-pdf-using-yahp.html

How to read string from .properties file in junit-tests?

I use wicket in my webapplication. I save the Strings in some .properties files as follows:
foo.properties
page.label=dummy
In the html-file, I can acces the String page.label as follows:
index.html
<wicket:message key="page.label">Default label</wicket:message>
Now I wrote some junit test cases for my Application and would like to access the Strings saved in the properties file. My Question is, how to read the String from the properties file?
Try this
import java.io.FileInputStream;
import java.util.Properties;
public class MainClass {
public static void main(String args[]) throws IOException {
Properties p = new Properties();
p.load(new FileInputStream("foo.properties"));
Object label = p.get("page.label");
System.out.println(label);
}
}
This section allow you to read all properties files from wherever you want and load them in the Properties
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class MainClass {
private static String PROPERTIES_FILES_PATHNAME = "file:///Users/ftam/Downloads/test/";// for mac
public static void main(String args[]) throws Exception {
Properties p = new Properties();
List<File> files = getFiles();
for(File file : files) {
FileInputStream input = new FileInputStream(file);
p.load(input);
}
String label = (String) p.get("page.label");
System.out.println(label);
}
private static List<File> getFiles() throws IOException, URISyntaxException {
List<File> filesList = new ArrayList<File>();
URL[] url = { new URL(PROPERTIES_FILES_PATHNAME) };
URLClassLoader loader = new URLClassLoader(url);
URL[] urls = loader.getURLs();
File fileMetaInf = new File(urls[0].toURI());
File[] files = fileMetaInf.listFiles();
for(File file : files) {
if(!file.isDirectory() && file.getName().endsWith(".properties")) {
filesList.add(file);
}
}
return filesList;
}
}
Wicket has its own way of localizing the resource, taking into account the component tree. See the javadoc for the StringResourceLoader.
One way of loading the Resource would be:
WicketTester tester = new WicketTester(new MyApplication());
tester.startPage(MyPage.class);
Localizer localizer = tester.getApplication().getResourceSettings()
.getLocalizer();
String foo = localizer.getString("page.label",tester.getLastRenderedPage(), "")
Using Apache Commons Configuration is a pretty good choice!
You can use load and then get("page.label")
Have this field inside your class:
import java.util.ResourceBundle;
private static ResourceBundle settings = ResourceBundle.getBundle("test",Locale.getDefault());
then a test.properties file like this:
com.some.name=someValueHere
Finally you can access the property values this way:
private String fieldName = settings.getString("com.some.name");

Categories