give read write permission to file [duplicate] - java

This question already has answers here:
How do I programmatically change file permissions?
(12 answers)
Closed 6 years ago.
hello guys I want to give file permission to open in read mode or write mode
.ext contains file extention and file_name contains name of file. f_p is a veriable where I an geting input as 'r' or 'w' mode. Here I am using same file at different locations
But in this code I am getting error as
cannot find symbol: method setReadable(boolean)
location: fos2 is of type FileOutputStream
<%
some code here
FileInputStream fis2 = new FileInputStream("e:/profile/epy/"+file_name+".ext");
FileOutputStream fos2 = new FileOutputStream("e:/decrypt/"+file_name+"."+ext);
if(f_p.equals("R")||f_p.equals("r"))
{
fos2.setReadable(true);
}
else if(f_p.equals("W")||f_p.equals("w"))
{
fos2.setWritable(true);
}
// some code here
%>
https://jsfiddle.net/wc8pccyL/

The current code uses the wrong class (FileOutputStream).
File f = new File(SOME_PATH);
if ("r".equalsIgnoreCase(f_p)) {
f.setReadable(true);
...
}
if ("w".equalsIgnoreCase(f_p)) {
f.setWritable(true);
...
}
However, one should be careful in assuming that one would want write access without read access. The assumption in the OP's code is that the f_p has a single value of "R" or "W", and sets the permission. This assumption should be carefully checked, especially across operating systems.
Also, if the FileOutputStream has to be used later (for actual output), it has a constructor that takes a File object, so there is nothing lost by creating the File object in such a scenario, and then creating the FileOutputStream fos = new FileOutputStream(f); where 'f' is the previously instantiated File object.

Related

java.io.FileNotFoundException but file exists [duplicate]

This question already has answers here:
How to solve the java.nio.file.NoSuchFileException?
(6 answers)
Closed 9 months ago.
I try to read a file from the resources and it tells me
java.io.FileNotFoundException: file:/home/simon/IdeaProjects/KTMBlockChain/build/resources/main/certificate_template.docx (No such file or directory)
Note that the file is blue and clickable. When I click on it it also opens the file so it definietly exists in the place expected.
Code:
InputStream in = null;
try {
File file = new File(this.getClass().getClassLoader().getResource("certificate_template.docx").toString());
in = new FileInputStream(file);
IXDocReport report = XDocReportRegistry.getRegistry().
loadReport(in, TemplateEngineKind.Freemarker);
Options options = Options.getTo(ConverterTypeTo.PDF).via(ConverterTypeVia.ODFDOM);
IContext ctx = report.createContext();
ctx.put("re_wo", pdfData.getReifen());
/*ctx.put("to", invoice.getTo());
ctx.put("sender", invoice.getInvoicer());
FieldsMetadata metadata = report.createFieldsMetadata();
ctx.put("r", invoice.getInvoiceRows());*/
report.convert(ctx, options, new FileOutputStream("result.pdf"));
I dont know what to do anymore...
EDIT 1: Changed code, still not working, another error code but same problem
There are
Disk files, class File;
Resource files (read-only), on the class path, possibly packed in a jar or war.
So here is you should use a resource, and Path is a generalisation of File, and all other kind of URL paths. This caused the error.
URL url = getClass().getClassLoader().getResource("certificate_template.docx");
Path path = Paths.get(url.toURI());
List<String> x = Files.readAllLines(path); // Reading a UTF-8 text.
But docx is not text, but a binary format (actually a zip format).
You either need to use a library or just handle the file as-is, like let the operating system open it.
You could use Files.readAllBytes(); reading UTF-8 will probably cause an error as the bytes are not in UTF-8 format.
After edit of question:
in = getClass().getClassLoader().getResourceAsStream("certificate_template.docx");

Why Do I Have to Enter the Full Path When Reading a File? [duplicate]

This question already has answers here:
Java, reading a file from current directory?
(8 answers)
Closed 2 years ago.
I am new to Java and come from a C++ background. I made a really simple code just to test out file reading. I have an input file called "input.txt" and its in the same file as my main file called "Main.java". However, when I try to create a new instance of a File object using the name "input. txt", it does not find the file and file.exists() returns false. When I instead put the full path name, it does find the file. The code is displayed below:
public static void main(String[] args) throws FileNotFoundException
{
// File file = new File("C:/Users/josep/OneDrive/Documents/java/input.txt"); //This works
File file = new File("input.txt"); //why won't this work?
if( file.exists() )
{
System.out.println("File exists");
}
else
{
System.out.println("Doesn't exist"); //this prints out.
}
Scanner input = new Scanner(file);
String str = input.nextLine();
System.out.println("Str: " + str);
input.close();
}
}
Am I doing something wrong here because I do not see why I shouldn't be able to just enter the file name instead of the full path. In C++, if the files were in the same folder I could just enter the file name so I'm confused as to why that is not working here. Below is the output I get:
Doesn't exist
Exception in thread "main" java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:211)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:153)
at java.base/java.util.Scanner.<init>(Scanner.java:639)
at Main.main(Main.java:22)
Can anyone help me understand what is going on? Any help would be greatly appreciated.
You can see where the path resolves to (which will be the dir held in System property "user.dir") as follows:
System.out.println(Path.of("index.txt").toRealPath());

Java: Referencing a file after being packaged (jar), getResourceAsStream? [duplicate]

This question already has an answer here:
Any way to get a File object from a JAR
(1 answer)
Closed 5 years ago.
I'm trying to implement a button into my project which, when clicked, automatically loads a specific file. Currently there are buttons for users selecting a file from their hard disk.
So, I downloaded the specific file and inserted it into the project. When using File f = new File("demofile") or something like this
getClass().getResource("/resources/file.txt").getFile(); the code WORKS locally.
However, when the project is packaged, a FileNotFoundException is thrown.
After much research online, there are suggestions to use something like:
InputStream is = getClass().getResourceAsStream("/resources/file.txt");
However, for this project, I need the file to be referenced as a file object so that it can be passed as an argument to other functions, such as:
in = new TextFileFeaturedSequenceReader(TextFileFeaturedSequenceReader.FASTA_FORMAT, file, DiffEditFeaturedSequence.class);
Any ideas on how I can solve this, or read a stream into a file object?
Thanks!
If you absolutely must pass a File, copy your resource to a temporary file:
Path path = Files.createTempFile(null, null);
try (InputStream stream =
getClass().getResourceAsStream("/resources/file.txt")) {
Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING);
}
in = new TextFileFeaturedSequenceReader(
TextFileFeaturedSequenceReader.FASTA_FORMAT,
path.toFile(),
DiffEditFeaturedSequence.class);
// Use the TextFileFeaturedSequenceReader as needed
// ...
Files.delete(path);

PrintWriter not outputing to file

Whenever the next segment of code is run, I get the new csv file created, but I don't get anything written to it:
PrintWriter fout = null;
try {
// create file
fout= new PrintWriter("EEGLogger.csv");
String headerFile = "IED_COUNTER, IED_INTERPOLATED, IED_RAW_CQ, IED_AF3, IED_F7, IED_F3, IED_FC5, IED_T7, " +
"IED_P7, IED_O1, IED_O2, IED_P8, IED_T8, IED_FC6, IED_F4, IED_F8, IED_AF4, " +
"IED_GYROX, IED_GYROY,IED_TIMESTAMP";
// Writes the header to the file
fout.println(headerFile);
fout.println();
...
I do a fout.close() in a finally statement, but that still doesn't help get any output to the file. Any ideas here?
Either:
You are looking in the wrong place, i.e. not the current working directory, or
You don't have write access to the current working directory.
If you had used a FileWriter and not got an IOException, that would rule out (2).
I've seen about a million answers and comments here this week claiming that the current working directory equals the location of the JAR file, but it doesn't.
You could open a FileWriter
fout = new PrintWriter(new FileWriter("EEGLogger.csv"));
...
fout.flush();
fout.close()
I believe the PrintWriter is intended for formatting and character encoding. api docs states Prints formatted representations of objects to a text-output stream and as well Methods in this class never throw I/O exceptions.
Using the FileWriter as parameter would force you to handle any IOException that may happen so if the file is not created or not writable, you will immediately get this information.
Another situation can happen if the file is created and you are just looking for the file at incorrect location. I'd suggest to create a File object too, to see where the file really resides (what's your real working directory)
File f = new File("EEGLogger.csv");
fout = new PrintWriter(new FileWriter(f));
System.out.println(f.getAbsolutePath());

Write String to text-file in java [duplicate]

This question already has answers here:
How do I save a String to a text file using Java?
(24 answers)
Closed 7 years ago.
Wanna save some information that I parse from a JSON to a plain text into a file and I also want this information to not be overwritten every time you run the program. It's suppose to work as a simple error logging system.
So far have I tried this:
FileWriter fileWriter = null;
File file = new File("/home/anderssinho/bitbucket/dblp-article-analyzer/logg.txt");
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
...
String content = "------------------------------------";
fileWriter = new FileWriter(file);
fileWriter.write(content);
//fileWriter.write(obj.getString("title"));
//fileWriter.write(obj.getString("creators"));
//fileWriter.write(article.GetElectronicEdition());
But when I do this it seems that I overwrite the information all the time and I'm also having problem to save the information I wanna grab from the JSON-array that I've got.
How can I do to make this work?
FileWriter fooWriter = new FileWriter(myFoo, false);
// true to append
// false to overwrite;
where myFoo is the File name
See this link
use append:
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("logg.txt", true)));
see this:
How to append text to an existing file in Java
Can you be more elaborate on this? If the problem is just not able to append then you can just add an argument to the FileWriter saying it to append and not write from the beginning.
Check the constructor here:
public FileWriter(String fileName, boolean append) throws IOException
Official Java Documentation:
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.
Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason

Categories

Resources