Save a File on a specific path - java

i have the current code:
public void crearArchivo(String nombre) {
archivo = new File(nombre.replaceAll("\\s", "") + ".txt");
if (!archivo.exists()) {
try {
archivo.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void crearCarpeta(String nombreCarpeta){
File directorio = new File(nombreCarpeta);
directorio.mkdir();
}
public void crearArchivoDatos(String nombreArchivo, ArrayList<String>datos) {
crearArchivo(nombreArchivo);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(archivo));
for (int i = 0; i < datos.size(); i++) {
bw.write(datos.get(i));
}
bw.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
the first method create a file only if it doesnt exist and the second one create a folder finally the third method save the data my problem is that i want to save some files on the folder i created first how can i set a path to save those file there, also i have the problem that this little program will execute at diferent computers so the path will change for any computer

You can get paths of folders on any computer using System.getProperty(...) - for example System.getProperty("user.home") gives you the current user directory (from which you can get to the desktop and other folders), and System.getProperty("user.dir") gives you the path of the folder from which your program is executed.

Creating or modifying files in Java can be done with the Java 8 NIO.2 methods.
Here is a link to the Oracle documentation : https://docs.oracle.com/javase/tutorial/essential/io/fileio.html
For your question, you have to declare a relative path, so it will be independent of the computer it will be executed on, rather than an absolute path, which begin on the root of the filesystem.

Related

Getting file not found exception when I file does exist [duplicate]

This question already has an answer here:
File not found java
(1 answer)
Closed 2 years ago.
I have a java project in eclipse and have a method that reads information from a file. When I do a JUnit test on the method, it is unable to find the file even though it is in my working tree and I used the correct class path declaration.
Method to read file:
public static ArrayList<Issue> readIssuesFromFile(String filename) {
ArrayList<Issue> issues = new ArrayList<Issue>();
try {
Scanner sc = new Scanner(new FileInputStream(filename));
String text = "";
while(sc.hasNextLine()) {
text+= sc.nextLine();
text+= "\n";
}
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
}
JUnit Test:
public void testReadIssueFromFile() {
String test = "test-files/valid_file.txt";
try {
ArrayList<Issue> issues = IssueReader.readIssuesFromFile(testFile);
assertEquals(issues.get(0).getIssueId(), 0);
} catch (Exception e) {
fail(e.getMessage());
}
}
Working Tree:
->Project
->src
->.java file containing method
->test
->JUnit test file
->test-files
->txt file
According to your working tree i think your path should be:
../test-files/valid_file.txt
The path you used (test-files/valid_file.txt) means search in the folder of your JUnit file a folder named test-files and search inside this folder a file named valid_file.txt.
According to your working tree it's not the case. So you need .. to move to the above level where you can find the folder test-files.
If it still doesn't work, maybe try to debug you program by printing the paths that you have used like this:
try {
/* Here you can replace the period with another path like "test-files/valid_file.txt"
* to see the absolute path of it
*/
System.out.print(new java.io.File( "." ).getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}

Recursing through a directory in java, I want to skip a step on the top level

I am trying to output a list of files within a directory recursively (not including the name of the name of the directory that I am starting with (just the contents of it and all files recursing down the tree after that)
here is what I have at the minute. It Might have errors here and there, but the idea is that it will print all the names of every file in the tree recursively. My problem is that I don't want it to print the name of the directory in which they live.
I think my problem is that I am using System.out.println at the start of the recursive method, which means it gets used every time. Which is desirable behavior for every directory BELOW the first one. Its an annoying little problem that I could use some help on. Thanks in advance.
public static void listFiles(String path)
{
File basedir = new File(path);
System.out.println(path.getName());
try
{
File[] files = basedir.listFiles();
for (File file : files)
{
// If Dealing with a directory, call recursively to the function
if (file.isDirectory())
{
listFiles(file.getPath());
}
else
{
System.out.println(file.getName());
}
}
}
catch(IOException ex)
{
System.out.println(ex);
}
}
public static void listFiles(String path, boolean firstCall)
{
File basedir = new File(path);
if(!firstCall)
{
System.out.println(path.getName());
}
try
{
File[] files = basedir.listFiles();
for (File file : files)
{
// If Dealing with a directory, call recursively to the function
if (file.isDirectory())
{
listFiles(file.getPath(), false); //false here because it is not the first call
}
else
{
System.out.println(file.getName());
}
}
}
catch(IOException ex)
{
System.out.println(ex);
}
}
Add a boolean parameter that specifies if it is the first call. When you call the method pass true to the parameter. Also path.getName() is not valid String doesn't have a function getName() maybe you meant basedir.getName()...also remove try catch block IOException can't occur there.

Trying to open Openoffice file using a link in java Toolkit

I tried to open from the normal eclipse it worked fine, but when exported same file to a jar
its giving an error.
Can anyone help?
public void mouseClicked(MouseEvent e) {
Process process;
try {
String resourceLocation = MainPanel.class.getProtectionDomain().getCodeSource().getLocation().getPath();
resourceLocation += "/com/microsoftplatformready/resources/images/endUserLicenseAgreement.docx";
process = Runtime.getRuntime().exec("soffice -reader "+resourceLocation);
process.waitFor();
process.destroy();
} catch (Exception e1) {
e1.printStackTrace();
}
}
Please help
Thanks
As Joop Eggen already said in the comment, first create a new temp file and copy your actual document to the temp file and open this one instead.
The reason is simply, Openoffice can't read files stored in an archive.
Path temp = Files.createTempFile("prefix", "suffix.ext");
Files.copy(getClass().getResourceAsStream(resourceLocation), temp);
process = Runtime.getRuntime().exec("soffice -reader "+ temp.toAbsolutePath().toString())

Java isn't getting files in a directory

System.out.println("READ");
String currentWorldName = "RANDOM";
String propertiesFileDirectory = propertiesFolder + currentWorldName + "/props.properties";
String entitiesFolderDirectory = propertiesFolder + currentWorldName + "/Entities";
try
{
properties.load(new FileInputStream(propertiesFileDirectory));
}
catch (FileNotFoundException e)
{
//Since it doesn't exist either it was deleted by the user or hasn't been created yet.
createNewPropertiesFile();
}
catch (IOException e)
{
outputToLog("IOException when loading properties file for the world: '" + currentWorldName + "'.\n" + e.getStackTrace().toString());
}
//getting values from properties
//Now to read each properties file in Entities
File entitiesFolder = new File(entitiesFolderDirectory);
try
{
List<String> entitiesDirectoryContents = Arrays.asList(entitiesFolder.list());
//Read each file in the entities directory and load it into memory.
for (String entityPropertiesFileName : entitiesDirectoryContents)
{
if (propertiesBelongsToEntityCH(entityPropertiesFileName))
{
//Get properties one way
}
else //The properties file we're working does not belong to CH.
{
//Get properties from the same file a different way
}
}
//This should never be hit since we have the file to read.
catch (FileNotFoundException e)
{
outputToLog("FileNotFoundException when loading entity properties file." + e.getMessage().toString());
}
//I don't know when/if this would be hit. It hasn't happened.
catch (IOException e)
{
outputToLog("IOException when loading entity properties file." + e.getMessage().toString());
}
catch (NullPointerException e)
{
entitiesFolder.mkdirs();
}
This HAS been working, I swear. It just started doing this.
Java keeps claiming that the "entitiesFolder" directory doesn't exist (I check with entitiesFolder.exists()). I have a solution for when that happens as you can see, because while my program is running it definitely can happen. Well it still claims that the folder doesn't exist, over and over.
I'm absolutely positive that it's the right directory because I print the "entitiesFolderDirectory" out to the console. It's correct. I can also be looking at the files inside of that folder and when mkdirs() runs it just deletes them all.
Java bug? This has completely broken my program.
I would write it without throwing a NullPointerException.
File entitiesFolder = new File(entitiesFolderDirectory);
entitiesFolder.mkdirs();
for (String entityPropertiesFileName : entitiesFolder.list()) {
//Do stuff
}
This will always work unless the folder could not be created.
What is the problem with this code? only one curly braces i found is missing else it is working fine.
This will create a dir test in c drive if does not exist else it will list the files in test dir over n over again
String entitiesFolderDirectory = "C:\\test";
File entitiesFolder = new File(entitiesFolderDirectory);
try
{
List<String> entitiesDirectoryContents = Arrays.asList(entitiesFolder.list());
for (String entityPropertiesFileName : entitiesDirectoryContents)
{
System.out.println(entityPropertiesFileName);
}
}catch (NullPointerException e)
{
System.out.println("creating new folder");
entitiesFolder.mkdirs();
}

Java desktop app cannot write a file on C:\ drive

I am trying to write a file on a C:\ drive, but I get an exception.
java.io.IOException: Access denied.
Code:
public class Test {
public static void main(String[] args) {
try {
StringBuilder sb = new StringBuilder(File.separator);
sb.append("index.txt");
// sb is "\\index.txt"
File f = new File(sb.toString());
boolean isCreated = f.createNewFile();
System.out.println(isCreated);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Actually, I get it, I don't have permission to write a file there, but I am quite sure it can be done somehow. If I had an applet, I'd just obtain a permission, but here, I don't know how to do it.
The probable solution may be checking if I can write a file there, but to check it I might try to write a file first adn then delete it in order to check if it is possible to write a file there, but I don't find this solution an optimal way.
The easiest way to check is to use File.canWrite().
Having said that, it looks like you're writing into the root of the drive. On Windows that's probably not a good idea, and you may want to consider writing elsewhere - e.g. a temp dir.
I have written a method, that takes a String to a directory, and checks, whether you can write a file out there:
static boolean canWrite(String folderPath) {
File file = new File(folderPath);
String new_file = "HastaLaVistaBaby";
if (file.isDirectory()) {
try {
new File(file + "\\" + new_file).createNewFile();
} catch (IOException e) {
return false;
}
new File(file + "\\" + new_file).delete();
return true;
} else {
return false;
}
}
To improve it, you may check, whether file.isFile() and get a parent directory and call this method.
This line should be:
sb.append("C:\\index.txt");
The extra backslash escapes a backslash.
Whether you hard-code a file name, like I did, or you get a file name from the user, you need the full path and file name.

Categories

Resources