I have met some strange trouble with reading file at Intellij Idea and on Windows 8.1.
And always I got FileNotFoundException.
Here is code snippet:
public XlsReader(String fileName, String sheetName) {
open(fileName, sheetName);
}
public void open(String fileName, String sheetName) {
InputStream fis = null;
try {
if (sheetName == null || sheetName.isEmpty()) {
throw new IllegalArgumentException("Please, provide sheet name");
}
Logger.logDebug("PATH: " + new File(".").getAbsolutePath());
fis = new FileInputStream(fileName);
String resourceFilePath = this.getClass().getResource(fileName).getFile();
Logger.logDebug(resourceFilePath);
fis = new FileInputStream(resourceFilePath);
XSSFWorkbook workBook = new XSSFWorkbook(fis);
sheet = workBook.getSheet(sheetName);
getMetaData();
I couldn't understand why at this line:
new FileInputStream(fileName)
I have got this exception.
And when chcenging path from:
xls = new XlsReader("InputDataIndirect.xlsx", "Calculator");
to:
xls = new XlsReader("test/InputDataIndirect.xlsx", "Calculator");
And it works now.
Here is project struckture:
I tried to load file from class path as well this.getClass().getResource(fileName).getFile() but it wasn't successful.
Any suggestions?
If you're running a main method or test from inside IntelliJ idea, it uses the root of the project as the root to load files from. Therefore, it will look under new_automation, so you need to add the test folder to your path.
To change this, you can change the working directory location in your run configuration to the location you want it to look in for files.
Related
I am opening a FileDialog, to let the user select an Audio file, in an MP3 file, and convert it to WAV, the error appears when I am trying to save the file in a new folder that I am creating
var dlg = new OpenFileDialog
{
DefaultExt = ".mp3",
Filter = "Audio files (.mp3)|*.mp3"
};
var res = dlg.ShowDialog();
if (res! == true)
{
var projectPath = Directory.GetParent(Directory.GetCurrentDirectory())?.Parent?.Parent?.FullName;
var FoderName = Path.Combine(projectPath!, "Audios");
Directory.CreateDirectory(FoderName);
using (var mp3 = new Mp3FileReader(dlg.FileName))
{
using (var ws = WaveFormatConversionStream.CreatePcmStream(mp3))
{
WaveFileWriter.CreateWaveFile(FoderName, was) // Error
System.UnauthorizedAccessException: 'Access to the path
'C:\XXX\XXX\XXX\XXX\XXX\XXX' is denied.'
}
}
Thanks
Inside some folders including "Program Files", an app usually has no permission to write a file. Therefore, it is recommended to use a folder dedicated for a specific purpose and made available for apps (you can get path to "Music" by Environment.GetFolderPath(Environment.SpecialFolder.MyMusic).
In general, an app must expect UnauthorizedAccessException when attempting to write a file and prepare a fallback for the case of that exception.
I want to apply unzipping the file using zipme cn1 library (codenameone library). Is there any examples on how to do it? Can anyone give me the starting point? So far I have tried the following code but I am not sure where to keep dataName.zip file in the project and the folder to keep all the files after unzipping.
#Override
protected void beforeMain(Form f) {
net.sf.zipme.ZipEntry dataZE;
InputStream isData = getClass().getResourceAsStream("/" + "dataName" + ".zip");
StringBuffer sbData = new StringBuffer();
ZipInputStream dataZIS = new ZipInputStream(isData);
try {
while ((dataZE = dataZIS.getNextEntry()) != null) {
//how to extract the zip file in a separate folder...
dataZIS.closeEntry();
}
} catch (IOException ex) {
System.out.println("zip exception");
}
}
The above code gives following error:
cannot find symbol
InputStream isData = getClass().getResourceAsStream("");
symbol: method getResourceAsStream(String)
One more thing, why cant I use the following to get the zip file as in core java
ZipInputStream zis = new ZipInputStream(new FileInputStream("C:\\abc.zip"));
// it gives "FileInputStream: cannot find symbol"
How can I extract the zip file in a separate folder?
You should use Display.getInstance().getResourceAsStream().
FileInputStream isn't supported in Codename One which uses FileSystemStorage. The FileInputStream and File API's assume many things about the underlying OS that aren't always true.
I am trying to create a file in current directory, the file name is based on the application name and the date, so far i am doing this but when i check the folder i dont see the file so the file is not created ...some one can help me please?
public File file;
public void initialize(URL url, ResourceBundle rb)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
Date date = new Date();
String currentDate = dateFormat.format(date);
String format = "Topology_"+ currentDate+".log";
String userDirectory = System.getProperty("user.dir");
String path = userDirectory+"\\"+format;
file = new File(path);
if((file.exists()))
{
System.out.println("file created");
}
}
First of all file.exits() does not create the file, what you are looking for is
boolean file.createNewFile()
Also
System.getProperty("user.dir")
does not return the current working directory, but the user folder.
Also i would suggest using the platform independent slash '/' instead of the windows only backslash '\'.
since I fixed the error I"ll provide an answer maybe it will help someone else :
file = new File(path) creates an instance of the file in memory, so the file doesn't exist on the disk yet. The error here is that my filename contain ":" character and that is forbidden , only when i created a BufferedWriter with an OutputStreamWriter i saw the file in the current folder(System.getProperty("user.dir")).
public void Uploader(string filename, Stream Data)
{
BinaryReader reader = new BinaryReader(Data);
string path = #"C:/Friendisc/Images";
FileStream fstream = new FileStream(path, FileMode.CreateNew);
BinaryWriter wr = new BinaryWriter(fstream);
wr.Write(reader.ReadBytes((int)Data.Length));
wr.Close();
fstream.Close();
Data.Close();
}
I am getting the error: Access to the path is denied.
What do I need to do?
Also How would I upload the image on another project within the same solution?
File path was not proper. Issue Resolved.
I need to change a couple paths from the debug/testing App.config files to their final home on the end user's machine. I see the XML File Changes option when editing the Installer project through Visual studio, and the help indicates I should Import the xml file to be changed.
BUT...
Is there any way to import the output of the project for the XML file? If I browse directly to the file itself I have to use the Debug or Release config file, which seems like it would be annoying. Otherwise I could use the base App.config but if any transformations are applied when building they'd be lost.
So am I stuck with just browsing to a file, or can I grab the "Project Output" somehow like I can for the .exe file?
XML File Changes is pretty weak tea.
To do what you are looking for your going to have to create a custom action that loads the .config file and updates it outside of InstallShield.
If you are using 2012 C# Wizard project type an option should be to create a .rul that catches the OnEnd() event in After Move Data. From the .rul call into a dll via UseDLL and invoke a method that accepts the target path to the config and the value to update the value to.
The following is code I'm testing so...
Using a C# Wizard project type I added the following InstallScript rule to call into a C# dll:
function OnEnd()
string basePath;
BOOL bResult;
string dllPath;
OBJECT oAppConfig;
begin
dllPath = TARGETDIR ^ APPCONFIG_DLL;
try
set oAppConfig = DotNetCoCreateObject(dllPath, "AppConfig.ConfigMgr", "");
catch
MessageBox("Error Loading" + dllPath + ": " + Err.Description, INFORMATION);
abort;
endcatch;
try
basePath = "C:\\Program Files (x86)\\MyCompany\\Config Test\\";
bResult = oAppConfig.ConfigureSettings(basePath + "appsettings.xml", basePath + "app.config", "someAppSection");
catch
MessageBox("Error calling ConfigureSettings " + dllPath + " " + Err.Number + " " + Err.Description, INFORMATION);
endcatch;
end;
C# test code:
public bool ConfigureSettings(string configFilePath, string targetAppConfigPath, string targetAppName)
{
bool completed = true;
try
{
XmlDocument configFileDoc = new XmlDocument();
configFileDoc.Load(configFilePath);
string installerTargetFileDoc = targetAppConfigPath; // InstallShield's build process for Visual Studio solutions does not rename the app.config file - Awesome!
System.IO.FileInfo fi = new System.IO.FileInfo(installerTargetFileDoc);
if (fi.Exists == false) installerTargetFileDoc = "app.config";
XmlDocument targetAppConfigDoc = new XmlDocument();
targetAppConfigDoc.Load(installerTargetFileDoc);
// ensure all required keys exist in the target .config file
AddRequiredKeys(configFileDoc.SelectSingleNode("configuration/" + targetAppName + "/requiredKeys"), ref targetAppConfigDoc);
// loop through each key in the common section of the configuration file
AddKeyValues(configFileDoc.SelectSingleNode("configuration/common/appSettings"), ref targetAppConfigDoc);
// loop through each key in the app specific section of the configuration file - it will override the standard configuration
AddKeyValues(configFileDoc.SelectSingleNode("configuration/" + targetAppName + "/appSettings"), ref targetAppConfigDoc);
// save it off
targetAppConfigDoc.Save(targetAppConfigPath);
}
catch (Exception ex)
{
completed = false;
throw ex;
}
return completed;
}
private void AddKeyValues(XmlNode configAppNodeSet, ref XmlDocument targetAppConfigDoc)
{
foreach (XmlNode configNode in configAppNodeSet.SelectNodes("add"))
{
XmlNode targetNode = targetAppConfigDoc.SelectSingleNode("configuration/appSettings/add[#key='" + configNode.Attributes["key"].Value + "']");
if (targetNode != null)
{
targetNode.Attributes["value"].Value = configNode.Attributes["value"].Value;
}
}
}
private void AddRequiredKeys(XmlNode targetAppNodeSet, ref XmlDocument targetAppConfigDoc)
{
foreach (XmlNode targetNode in targetAppNodeSet.SelectNodes("key"))
{
// add the key if it doesn't already exist
XmlNode appNode = targetAppConfigDoc.SelectSingleNode("configuration/appSettings/add[#key='" + targetNode.Attributes["value"].Value + "']");
if (appNode == null)
{
appNode = targetAppConfigDoc.SelectSingleNode("configuration/appSettings");
XmlNode newAddNode = targetAppConfigDoc.CreateNode(XmlNodeType.Element, "add", null);
XmlAttribute newAddNodeKey = targetAppConfigDoc.CreateAttribute("key");
newAddNodeKey.Value = targetNode.Attributes["value"].Value;
XmlAttribute newAddNodeValue = targetAppConfigDoc.CreateAttribute("value");
newAddNodeValue.Value = "NotSet";
newAddNode.Attributes.Append(newAddNodeKey);
newAddNode.Attributes.Append(newAddNodeValue);
appNode.AppendChild(newAddNode);
}
}
}
While it seems like it should work, Installshield is unable to grok project output correctly (dependencies are missed often, merge modules are duplicated even when they dont apply), or give you a way to deal with individual files in project output.
I have no less than 5 bugs open with them about problems using project output and their workaround is always "Add the files manually".
If you are just getting started with install shield, I suggest you try another alternative. If you have to use it, either complain about this not working to their support team and use the suggested workaround until they get it together.
This may not be the "answer" to your question, but hopefully helps your sanity when dealing with the broken feature set in this product.
You can import any file you want (by browsing), and make changes to it in any run-time location you like. I suggest just putting the minimal amount you need to make your changes; after all it's the XML File Changes view. That way most updates to the file won't cause or require any changes to your XML File Changes settings, no matter how it's included.