Permission denied when trying to write with FileWriter/BufferedWriter in java. - java

im really struggling one this one. Basically im working with a couple of my classmates to a project where we have to deliver a space wars remake and we implemented a single player mode where you can actually get scores. problem is i can read my file but cannot write on it. ive tryed with all the system i could find online but didn't manage to get the error solved. here is the code of the class that manages the highscore system. i even tryed creating the file with code and tryed deleting it and recreating an empty one. the file is in the home directory of the project right now. the metods readFile and getHighscores work but the check one always gets stuck in the writing part.
the error i get is " Il privilegio richiesto non appartiene al client
[Ljava.lang.StackTraceElement;#6eb60ef7"
which translates in "The requested privilege does not belong to the client"
Keep in mind it's all in a git repository where i should have all the permissions but it's basically the only idea left in my mind.
package controller;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
/**
*the creation of the HighscoreManager class.
*/
public class HighscoreManager {
private static final int LAST_HIGHSCORE_INDEX = 9;
private static final String FILE_NAME = "/Highscores.txt";
private ArrayList<Integer> highscores = new ArrayList<Integer>();
/**
* reads the file and loads the highscore list.
*/
private void readFile() {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
String s;
highscores.clear();
try {
is = this.getClass().getResourceAsStream(FILE_NAME);
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((s = br.readLine()) != null) {
highscores.add(Integer.parseInt(s));
}
if(br!=null && isr !=null && is!= null) {
br.close();
isr.close();
is.close();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
/**
* checks if the passed score is an actual highscores.
* #param score
*/
public void checkHighscores(final int score) {
readFile();
File file = new File(FILE_NAME);
boolean newHighscoreFound = false;
for (int i = 0; i < highscores.size(); i++) {
if (score > highscores.get(i)) {
newHighscoreFound = true;
break;
}
}
if (newHighscoreFound) {
highscores.add(LAST_HIGHSCORE_INDEX, score);
Collections.sort(highscores);
Collections.reverse(highscores);
for (int i : highscores) {
System.out.println(i);
}
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
for(int i : highscores) {
bw.write(i);
}
} catch(IOException e) {
System.out.println(e.getStackTrace());
} finally {
if(fw != null && bw != null) {
try {
fw.close();
bw.close();
} catch (IOException e) {
System.out.println(e.getStackTrace());
}
}
}
}
}
/**
* returns an array list of strings containing all the current highscores.
* #return toBeReturned
*/
public ArrayList<String> getHighscores() {
ArrayList<String> toBeReturned = new ArrayList<>();
try {
highscores.clear();
readFile();
for (int i : highscores) {
toBeReturned.add(String.valueOf(i));
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
System.out.println("There you have your highscores.");
}
return toBeReturned;
}
}

You don't need to access the Class object to load a file (or indeed the associated ClassLoader). Just use normal Java IO.
To read your set of high scores:
highScores = Files.lines(Paths.get(FILE_NAME))
.map(Integer::parseInt)
.collect(Collectors.toList());
To write a new set of high scores:
Files.write(Paths.get(FILE_NAME), highScores.stream()
.map(String::valueOf)
.collect(Collectors.toList()));
(Also, why is this tagged with "git"?)

Related

JAVA - not able to update data in file that is "resources" folder

I am a little perplexed by the behavior I see in my proof-of-concept test program.
My Java application uses a file that is placed in "resource" folder in the Java project. The application will occasionally read numeric data from it, use it, increment the number and write it back to the same file for the next cycle.
The following test application mimics the above (wanted) behavior:
public class ReadWriteFile {
private static final String TEMP_EMAIL_ID_DATAFILE_PATH = "main/resources/TempEmailId.dat";
public static void main(String[] args) throws ParseException {
try {
int id = readTempId();
System.out.println("Current value = " + id);
writeTempId(id+5);
System.out.println("Updated value = " + readTempId());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int readTempId() throws IOException {
InputStream is = ReadWriteFile.class.getClassLoader().getResourceAsStream(TEMP_EMAIL_ID_DATAFILE_PATH);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
int currentValue = 0;
while ((line = br.readLine()) != null) {
currentValue = Integer.parseInt(line);
}
br.close();
return currentValue;
}
public static void writeTempId(int currentId) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("src" + File.separator + TEMP_EMAIL_ID_DATAFILE_PATH));
bw.write(Integer.toString(Math.abs(currentId)));
bw.flush();
bw.close();
return;
}
}
When I run the test, the following is seen:
Current value = 100000054
Updated value = 100000054
My gut feeling is that the use of
ReadWriteFile.class.getClassLoader().getResourceAsStream(TEMP_EMAIL_ID_DATAFILE_PATH);
is causing the issue. I am using this to access the file within the JAVA project.
Can it be true?
Also, note that for creating the BufferedWriter object, I have to pre-pend the Java constant with "src/" - else the file could not be found :(
Thanks.
Resources are intended to be read-only. The only way they could become writable is if they were extracted into the file system, but that's not how they are intended to be used and is not portable as resources are normally in a jar. Write to a file instead
This should work:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.ParseException;
public class ReadWriteFile {
private static final String TEMP_EMAIL_ID_DATAFILE_PATH = "TempEmailId.dat";
public static void main(String[] args) throws ParseException, URISyntaxException {
try {
int id = readTempId();
System.out.println("Current value = " + id);
writeTempId(id+5);
System.out.println("Updated value = " + readTempId());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int readTempId() throws IOException {
InputStream is = ReadWriteFile.class.getClassLoader().getResourceAsStream(TEMP_EMAIL_ID_DATAFILE_PATH);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
int currentValue = 0;
while ((line = br.readLine()) != null) {
currentValue = Integer.parseInt(line);
}
br.close();
return currentValue;
}
public static void writeTempId(int currentId) throws IOException, URISyntaxException {
URL resource = ReadWriteFile.class.getClassLoader().getResource(TEMP_EMAIL_ID_DATAFILE_PATH);
File file = new File(resource.toURI());
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(Integer.toString(Math.abs(currentId)));
bw.flush();
bw.close();
return;
}
}
The 2 key lines for writing to file was doing it as such:
URL resource = ReadWriteFile.class.getClassLoader().getResource(TEMP_EMAIL_ID_DATAFILE_PATH);
File file = new File(resource.toURI());

How to figure out why file is missing when trying to Run Configurations (set an Argument in Java)?

Hello everyone, Java beginner here. I am trying to run some java code in eclipse IDE, and set my args x = 25 from
Run > Run Configurations > Arguments > Apply > Run. However, before I can get to Arguments, I get this error message (see photo below). Does anyone know what this means or why I am getting this? What does this specific '.metadata/.plugins/org.eclipse.debug.core' do?
MY CODE BELOW:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class IOTest {
public IOTest () {
}
public void readFile () {
try {
FileReader file = new FileReader("movies.txt");
BufferedReader br = new BufferedReader(file);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (Exception e) {
System.out.println("Unable to load file.");
}
}
public void writeFile () {
try {
FileWriter file = new FileWriter("tvshows.txt");
BufferedWriter bw = new BufferedWriter(file);
bw.write("Seinfeld\n");
bw.write("Breaking Bad\n");
bw.write("The Simpsons\n");
bw.write("Family Guy\n");
bw.close();
} catch (Exception e) {
System.out.println("Unable to load/create file.");
}
}
public static void main(String[] args) {
IOTest test = new IOTest();
test.readFile();
test.writeFile();
if (args.length == 1) {
// Do something.
int x = Integer.parseInt(args[0]);
System.out.println("x = " + x);
} else {
// Do something else.
}
}
}

Could it not delete the entire file content while saving into file? Java [duplicate]

This question already has answers here:
PrintWriter append method not appending
(5 answers)
Closed 4 years ago.
I've recently made a Snake game with function that allows to store and find the best score of his. But unfortunetely it every time it saves your score into file, it deletes the previous file content. Is there any way to avoid that? As it is visible in the code below, I've made 3 methods. The first one is to save your score into a file. Last ones are to find the best score.
package matajus.snake;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Score {
private File file;
public static int score;
private static final String fileName = "BestScores.txt";
public Score() {
file = new File(fileName);
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void saveToFile() throws FileNotFoundException {
PrintWriter print = new PrintWriter(fileName);
print.println(score);
print.close();
}
public int findBestScore() {
List<Integer> lines = new ArrayList<Integer>();
Scanner input;
int bestScore = 0;
try {
input = new Scanner(file);
if(linesNumber() > 0) {
for(int i = 0; i < linesNumber(); i++) {
String readLine = input.nextLine();
int line = Integer.parseInt(readLine);
lines.add(line);
}
bestScore = Collections.max(lines);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bestScore;
}
private int linesNumber() throws FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
int lines = 0;
try {
while((line = reader.readLine()) != null) {
lines++;
}
} catch (Exception e) {
e.printStackTrace();
}
return lines;
}
}
PrintWritter will truncate the file: https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.lang.String)
Have a look at the proposed solution here: How to append text to an existing file in Java

How to check if file content is empty

I am trying to check if a file content is empty or not. I have a source file where the content is empty.
I tried different alternatives.But nothing is working for me.
Here is my code:
Path in = new Path(source);
/*
* Check if source is empty
*/
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(in)));
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br.readLine().length() == 0) {
/*
* Empty file
*/
System.out.println("In empty");
System.exit(0);
}
else{
System.out.println("not empty");
}
} catch (IOException e) {
e.printStackTrace();
}
I have tried using -
1. br.readLine().length() == 0
2. br.readLine() == null
3. br.readLine().isEmpty()
All of the above is giving as not empty.And I need to use -
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(in)));
} catch (IOException e) {
e.printStackTrace();
}
Instead of new File() etc.
Please advice if I went wrong somewhere.
EDIT
Making little more clear. If I have a file with just whitespaces or
without white space,I am expecting my result as empty.
You could call File.length() (which Returns the length of the file denoted by this abstract pathname) and check that it isn't 0. Something like
File f = new File(source);
if (f.isFile()) {
long size = f.length();
if (size != 0) {
}
}
To ignore white-space (as also being empty)
You could use Files.readAllLines(Path) and something like
static boolean isEmptyFile(String source) {
try {
for (String line : Files.readAllLines(Paths.get(source))) {
if (line != null && !line.trim().isEmpty()) {
return false;
}
}
} catch (IOException e) {
e.printStackTrace();
}
// Default to true.
return true;
}
InputStream is = new FileInputStream("myfile.txt");
if (is.read() == -1) {
// The file is empty!
} else {
// The file is NOT empty!
}
Of course you will need to close the is and catch IOException
You can try something like this:
A Utility class to handle the isEmptyFile check
package com.stackoverflow.answers.mapreduce;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class HDFSOperations {
private HDFSOperations() {}
public static boolean isEmptyFile(Configuration configuration, Path filePath)
throws IOException {
FileSystem fileSystem = FileSystem.get(configuration);
if (hasNoLength(fileSystem, filePath))
return false;
return isEmptyFile(fileSystem, filePath);
}
public static boolean isEmptyFile(FileSystem fileSystem, Path filePath)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(fileSystem.open(filePath)));
String line = bufferedReader.readLine();
while (line != null) {
if (isNotWhitespace(line))
return false;
line = bufferedReader.readLine();
}
return true;
}
public static boolean hasNoLength(FileSystem fileSystem, Path filePath)
throws IOException {
return fileSystem.getFileStatus(filePath).getLen() == 0;
}
public static boolean isWhitespace(String str) {
if (str == null) {
return false;
}
int length = str.length();
for (int i = 0; i < length; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
public static boolean isNotWhitespace(String str) {
return !isWhitespace(str);
}
}
Class to test the Utility
package com.stackoverflow.answers.mapreduce;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
public class HDFSOperationsTest {
public static void main(String[] args) {
String fileName = "D:/tmp/source/expected.txt";
try {
Configuration configuration = new Configuration();
Path filePath = new Path(fileName);
System.out.println("isEmptyFile: "
+ HDFSOperations.isEmptyFile(configuration, filePath));
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}

How can i remove a word/line and replace it with a new one in a txt file (Java)?

For example we have a .txt file:
Name smth
Year 2012
Copies 1
And I want to replace it with that:
Name smth
Year 2012
Copies 0
Using java.io.*.
Here is the code that does that. Let me know if you have any question.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;
public class Test2 {
Map<String, String> someDataStructure = new LinkedHashMap<String, String>();
File fileDir = new File("c:\\temp\\test.txt");
public static void main(String[] args) {
Test2 test = new Test2();
try {
test.readFileIntoADataStructure();
test.writeFileFromADataStructure();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void readFileIntoADataStructure() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(fileDir)));
String line;
while ((line = in.readLine()) != null) {
if (line != null && !line.trim().isEmpty()) {
String[] keyValue = line.split(" ");
// Do you own index and null checks here this is just a sample
someDataStructure.put(keyValue[0], keyValue[1]);
}
}
in.close();
}
private void writeFileFromADataStructure() throws IOException {
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileDir)));
for (String key : someDataStructure.keySet()) {
// Apply whatever business logic you want to apply here
myBusinessMethod(key);
out.write(key + " " + someDataStructure.get(key) + "\n");
out.append("\r\n");
out.append("\r\n");
}
out.flush();
out.close();
}
private String myBusinessMethod(String data) {
if (data.equalsIgnoreCase("Copies")) {
someDataStructure.put(data, "0");
}
return data;
}
}
Read your original text file line by line and separate them into string tokens delimited by spaces for output, then when the part you want replaced is found (as a string), replace the output to what you want it to be. Adding the false flag to the filewrite object ("filename.txt", false) will overwrite and not append to the file allowing you to replace the contents of the file.
this is the code to do that
try {
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader("yourFolder/theinputfile.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("yourFolder/theinputfile.txt" , false));
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.indexOf("Copies")>=0){
bw.write("Copies 0")
}
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close()bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
hopefully that help

Categories