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")).
Related
I was wondering if it is possible with xamarin.forms to download any type of file to the device.. de files are stored on Azure, i get a Memorystream of the file, its very important for my app. my question excists of 2 parts actually,
how to download de file to the device of the user?,
and how to show the file of Any type in a default application of the type ( like pdf reader)
this is what i tried
MemoryStream memoryStream = AzureDownloader.DownloadFromAzureBlobStorage(null, doc.azure_container, doc.file_path, ref filen, true);
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = doc.filename;
string localPath = Path.Combine(documentsPath, localFilename);
File.WriteAllBytes(localPath, memoryStream.ToArray()); // this is a try to save to local storage
any help appreciated
how to download the file to the device of the user?
Use PCLStorage as its cross-platform and would work for iOS and Android:
public async Task CreateRealFileAsync()
{
// get hold of the file system
IFolder rootFolder = FileSystem.Current.LocalStorage;
// create a folder, if one does not exist already
IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder", CreationCollisionOption.OpenIfExists);
// create a file, overwriting any existing file
IFile file = await folder.CreateFileAsync("MyFile.txt", CreationCollisionOption.ReplaceExisting);
// populate the file with some text
await file.WriteAllTextAsync("Sample Text...");
}
how to show the file of Any type in a default application of the type
( like pdf reader)
this is too broad and could have several solutions depending on what exactly you want to achieve.
Hope this helps
I'm trying to find all the wavs in every folder that I have in a directory, for example, "Music". Right now, my code shows the wavs found in whatever folder I select, but I want it to list all the wavs found in the whole directory at once, without the user going from folder to folder. How can I do that? Here's my code:
FileChooser chooseFile = new FileChooser();
FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Choose a file (*.wav)", "*.wav");
chooseFile.getExtensionFilters().add(filter);
File file = chooseFile.showOpenDialog(null);
directory = file.toURI().toString();
First you should use a DirectoryChooser to select a directory. You can use the NIO package to find the files:
DirectoryChooser chooser = new DirectoryChooser();
File directory = chooser.showDialog(null);
Path[] wavs = findWavs(directory);
private static Path[] findWavs(File directory) throws IOException {
Path dir = directory.toPath();
try (Stream<Path> stream = Files.find(dir, Integer.MAX_VALUE, (path, attributes) -> path.getFileName().toString().endsWith(".wav"))) {
return stream.toArray(Path[]::new);
}
}
If you need Files instead you could simply map the paths to files:
return stream.map(Path::toFile).toArray(File[]::new);
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.
I am using jdeveloper version 11.1.1.5.0. In my use case I have created Mail Client Send Mail program where I used ADF InputFile component to attach File on mail.
But problem is that InputFile Component only return path of file(only get file name). And in my mail program DataSource class use full path to access file name.
UploadedFile uploadfile=(UploadedFile) actionEvent.getNewValue();
String fname= uploadfile.getFilename();//this line only get file name.
So how can I get full path using adf InputFile component or any other way to fulfill my requirement.
You could save the uploaded file in a path at the server. Only take care about naming that file, because of concurrency of users you should follow a policy about it, for example, adding te time in milliseconds to the name of the file. Like this...
private String writeToFile(UploadedFile file) {
ServletContext servletCtx =
(ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext();
String fileDirPath = servletCtx.getRealPath("/files/tmp");
String fileName = getTimeInMilis()+file.getFilename();
try {
InputStream is = file.getInputStream();
OutputStream os =
new FileOutputStream(fileDirPath + "/"+fileName);
int readData;
while ((readData = is.read()) != -1) {
os.write(readData);
}
is.close();
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return fileName;
}
This method also returns the new name of the uploaded file. You can replace getTimeInMilis() with any naming policy you like.
It would be a security issue if a web app is able to see anything other than the data stream for an uploaded file. The directory structure of the client would not be exposed to the webapp. As such, unless you plan to upload the file from the same host as the server, you will not have access to the file path on the client.
Note: Using answer instead of comment due to reputation threshold
I am working on an application that stores files under /WEB-INF/someFolder/. But I dont find the right way to create files under this folder. I did this, but it is not working:
File newFile = new File("/WEB-INF/fileName.xml");
When I try to check the creation:
boolean isCreated = newFile.createNewFile();
I get :
java.io.IOException: No such file or directory
Please help me doing it in the right way.
Update:
I did this workaround, it is working but I dont see that it is performant solution.
ServletContext servletContext = getServletContext();
String path = servletContext.getRealPath("/WEB-INF/");
File newFile2 = new File(path+"/fileName.xml");
Any ideas?
You shall use ServletContext.getRealPath(String) and build the entire classpath manually
String webInfPath = getServletConfig().getServletContext().getRealPath("WEB-INF");
OR go step by step:
ServletConfig scfg= getServletConfig();
ServletContext scxt = scfg.getServletContext();
String webInfPath = sxct.getRealPath("WEB-INF");
And than use the webInfPath to create a File object inside WEB-INF
File newFile = new File(webInfPath + "/fileName.xml");
make sure you applaction have the permissions to write.
you can get the path ues like this:
String path=Thread.currentThread().getContextClassLoader().getResource("com/youpackage/");
Now you get the path which is your class folder path,so you can get the WEB-INF path.
ps: i remember when create file you must writer some content,otherwies it may not create.