I have figured out how to create a hidden file in Java, now I need to write large amounts of data to the file. I keep getting the following exception:SEVERE: java.io.FileNotFoundException: <filepath>\tmp (Access is denied)
Here are two approaches I took to get try and get a solution, but I get the same exception for both approaches. Note: toOverwrite is the hidden file in both cases.
File fileByteText = new File("./testFile.txt");
File toOverwrite = new File("./tmp");
//Assume toOverwrite is hidden
boolean toReturn = true;
try {
byte[] fileByteText = FileUtils.readFileToByteArray(toGetTextFrom);
FileUtils.writeByteArrayToFile(toOverwrite, fileByteText, false);
toReturn = false;
} catch (IOException e) {
bam.severe(e);
toReturn = true;
}
Approach two using the same file objects:
try {
String fileText = FileUtils.readFileToString(toGetTextFrom);
FileWriter fw = new FileWriter(toOverwrite.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fileText);
bw.close();
toReturn = false;
} catch (IOException e1) {
bam.severe(e1);
toReturn = true;
}
You can get an Exception when you try to write to a file of type directory.
Check what method toOverWrite.isFile() returns;
if false you cannot write.
There is no magic in Unix. Just prepend a . to your filename. Under Windows, this cannot be achieved with Java. You need native commands. May this works with NIO2.
Related
I have Server-Client messenger - not important - and I have a settings file to store the settings, but for some reason when I run the code, the settings file clears.
Here is the code that makes the settings file and directory:
boolean exists = new File(System.getProperty("user.home")+"\\Documents\\Messenger Server").mkdir();
File directory = new File(System.getProperty("user.home")+"\\Documents\\Messenger Server");
File settingsFile = new File(System.getProperty("user.home")+"\\Documents\\Messenger Server\\settings.txt");
if(exists){
try {
directory.createNewFile();
System.out.println("Created");
} catch (IOException e) {
e.printStackTrace();
}
}
if(!settingsFile.exists()){
try {
settingsFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Created Settings.txt");
System.out.println(settingsFile.getAbsolutePath());
}
And this is the code that reads and writes to the file:
try {
FileReader fileReader = new FileReader(settingsFile);
FileWriter fileWriter = new FileWriter(settingsFile);
BufferedReader bf = new BufferedReader(fileReader);
BufferedWriter bw = new BufferedWriter(fileWriter);
}catch(IOException b){
b.printStackTrace();
}
ArrayList<String> settingList = new ArrayList<String>();
for (int i = 0; i < 6; i++) {
try {
settingList.add(bf.readLine());
} catch (IOException ex) {
ex.printStackTrace();
}
}
if(!settingList.get(0).equals("alwaysOnTop=true")&&!settingList.get(0).equals("alwaysOnTop=false")){
try {
bw.write("alwaysOnTop=false");
} catch (IOException ex) {
ex.printStackTrace();
}
}
The FileWriter constructor can take a boolean argument ( FileWriter(File file, boolean append) ), which if true makes the FileWriter append to the file instead of overwriting it every time. Like this:
FileWriter fileWriter = new FileWriter(settingsFile, true);
The answer from #JustusG is correct.
Still, I would not recommend using .txt files to keep the settings of your app.
Since they are hard to maintain, you may have duplicate settings (because of appending...) and so on.
I would recommend using .properties files. At the end of the day they do the same thing, it's just that .properties files have classes to read and to write your settings/properties.
Here is an example:
Properties prop = new Properties();
File propFile = new File("path/to/app.properties");
InputStream in = new FileInputStream(propFile); // Open the prop file
prop.load(in); // Load it in the Properties object
prop.setProperty("setting1", "value1"); // Setting a new setting to what you need OR setting an old setting to a new value.
String value2 = prop.getProperty("setting2"); // Reading a property
//And at the end, writing the properties that you changed (without duplicates)
prop.store(new FileOutputStream("xyz.properties"), null);
I'm running into a filenotfound when trying to read a file in internal storage; I'm pretty darn sure the file exists where I expect it and with appropriate permissions
I'm creating an android app where I'm saving off a string array list into files on the app's internal storage and then trying to randomly access the various lines from the file. I'm writing the file and reading the file within the same class, so I feel like I shouldn't have issues with like filepath and naming conventions.
Things I've verified or tried:
I've opened the files from the Android Device Monitor and the
contents and location are as expected.
The file permissions are -rw-rw----
I've grabbed the user.dir in both the read and write method and they both return "/" which seems incorrect, but the write method works (since the file is there)
Checked a ton of examples to double check formatting (for filename and for method use)
Read the File java reference texts as well as the android storage reference text
file name with and without ".txt"
I feel like I could probably hard code in the path but that sounds like a bad plan and shouldn't be necessary
Anyway here's wonderwall (or rather my code, but only the code parts that seemed relevant)
final List<String> affirmList = copyFilesToList("affirmation_file.txt");
final List<String> suggestList = copyFilesToList("suggestion_file.txt");
//copyFilesToList tries to open the file via selectSuggestion, if it is empty or fails, it goes into the create method
//opens both files and unpacks them into array list, feeds to unpack mehtods
private List<String> copyFilesToList(String fileName) {
String line="";
List<String> arr = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {
while ((line = bufferedReader.readLine()) != null) {
arr.add(line);
}
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
arr.add("IO exception");
} finally {
//close stream
}
//test if arr contains something
//if not send to addDefaultLines
if (arr.isEmpty()){
arr = addDefaultLines(fileName);
}
return arr;
}
//
private List<String> addDefaultLines(String fileName){
List<String> arr = new ArrayList<String>(); //create arraylist
if (fileName=="affirmation_file.txt") {
//load affirmation values into arraylist
arr.add("affirmation 1");
arr.add("affirmation 2");
}
if (fileName=="suggestion_file.txt"){
//load suggestion values into arraylist
arr.add("suggestion 1");
arr.add("suggestion 2");
}
//sync arraylist with file
try{
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
String list = "";
int sz=arr.size();
//put the arraylist into a single string, for clarity
for (int i = 0; i < sz; i++) {
list += arr.get(i) + "\n"; //append with line breaks between
}
fos.write(list.getBytes());
}
catch (java.io.IOException e) {
e.printStackTrace();
}
return arr;
}
So, here's the problem: I'm working on a Java program that reads from a .csv file, and constructs objects out of it. I'm using InputStream, InputStreamReader, and BufferedReader to read the file. The IDE I'm using is NetBeans and the file being read is in the src directory. A quick note, for your convenience, I hardcoded the filename, so that you would understand how it's actually being read. In my actual program, the filename is being passed in as a parameter of the method. Anyways, it seems to work fine in the IDE. But when I create a JAR, it doesn't do what I want it to do.
public void readFile(filename) throws IOException, FileNotFoundException {
is = getClass().getResourceAsStream("file.csv");
isr = new InputStreamReader(is);
//fr = new FileReader(filename);
br = new BufferedReader(isr);
String info;
while ((info = br.readLine()) != null)
{
String[] tokens = info.split(",");
Object object = new Object();
object.setProperty(tokens[0]);
object.setAnotherProperty(tokens[1]);
object.setSomeOtherProperty(tokens[2]);
}
}
catch (FileNotFoundException f)
{
f.getMessage();
}
catch (IOException ioe)
{
ioe.getMessage();
}
catch (ArrayIndexOutOfBoundsException oob)
{
//;
}
catch (NullPointerException npe)
{
//;
}
finally
{
br.close();
isr.close();
is.close();
}
My method to update the file looks like this(once again, the filename has been hardcoded so you could better understand what's going on):
public void updateRoom(String filename, String property1, string property2, string property3) throws FileNotFoundException
{
for (Objects o : objects)
{
if (o.getProperty().equals(property1))
{
o.setProperty(property1);
o.setAnotherProperty(property2);
o.setSomeOtherProperty(property3);
}
}
File file = new File("file.csv");
PrintWriter pr = new PrintWriter(file);
for (Object o : objects)
{
pr.println(o.getProperty() + "," +
o.getAnotherProperty() + "," +
o.getSomeOtherProperty())
}
pr.close();
}
The problem is that the .JAR reads the file when I run it, but instead of writing to the SAME file, it simply creates a new one and writes to that one. It's a problem because every time I run the program again, the properties and values remain unchanged. It's NOT reading from the newly-created file. It's still reading from the original file, but it's writing to a new file.
I want to READ AND WRITE to the same file. That way, if I close the program and run it again, it will have the new properties/values already loaded in.
I am working on a simple save system for my game, which involves three methods, init load and save.
This is my first time trying out reading and writing to/from a file, so I am not sure if I am doing this correctly, therefore I request assistance.
I want to do this:
When the game starts, init is called. If the file saves does not exist, it is created, if it does, load is called.
Later on in the game, save will be called, and variables will be written to the file, line by line (I am using two in this example.)
However, I am stuck on the load function. I have no idea what do past the point I am on. Which is why I am asking, if it is possible to select a certain line from a file, and change the variable to that specific line.
Here is my code, like I said, I have no idea if I am doing this correctly, so help is appreciated.
private File saves = new File("saves.txt");
private void init(){
PrintWriter pw = null;
if(!saves.exists()){
try {
pw = new PrintWriter(new File("saves.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else{
try {
load();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void save(){
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream(new File("saves.txt"), true));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
pw.println(player.coinBank);
pw.println(player.ammo);
pw.close();
}
public void load() throws IOException{
BufferedReader br = new BufferedReader(new FileReader(saves));
String line;
while ((line = br.readLine()) != null) {
}
}
I was thinking of maybe having an array, parsing the string from the text file into a integer, putting it into the array, and then have the variables equal the values from the array.
Seems like your file is a key=value structure, I suggest you'll use Properties object in java.
Here's a good example.
Your file will look like this:
player.coinBank=123
player.ammo=456
To save:
Properties prop = new Properties();
prop.setProperty("player.coinBank", player.getCoinBank());
prop.setProperty("player.ammo", player.getAmmo());
//save properties to project root folder
prop.store(new FileOutputStream("player.properties"), null);
Then you'll load it like this:
Properties prop = new Properties();
prop.load(new FileInputStream("player.properties"));
//get the property value and print it out
System.out.println(prop.getProperty("player.coinBank"));
System.out.println(prop.getProperty("player.ammo"));
Reading and writing are pretty much symmetric.
You're writing player.coinBank as the first line of the file, and player.ammo as the second line. So, when reading, you should read the first line and assign it to player.coinBank, then read the second line and assign it to player.ammo:
public void load() throws IOException{
try (BufferedReader br = new BufferedReader(new FileReader(saves))) {
player.coinBank = br.readLine();
player.ammo = br.readLine();
}
}
Note the use of the try-with-resources statement here, which makes sure the reader is closed, whatever happens in the method. You should also use this construct when writing to the file.
I'm trying to open a file in android like this :
try
{
FileInputStream fIn = context.openFileInput(FILE);
DataInputStream in = new DataInputStream(fIn);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
if(in!=null)
in.close();
}
catch(Exception e)
{ }
, but in case the file does not exists a file not found exception is thrown . I'd like to know how could I test if the file exists before attempting to open it.
I think the best way to know if a file exists, without actually trying to open it, is as follows:
File file = getContext().getFileStreamPath(FILE_NAME);
if(file.exists()) ...
The documentation says Context.openFileInput either returns an inputStream (file found) or throws a FileNotFoundException (not found)
http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
So it looks like the exception is your "test".
You could also try using standard
java.io.File file = new java.io.File(PATHTOYOURCONTEXT , FILE);
if (file.exists()) {
FileInputStream fIn = new FileInputStream(file);
}
But that is not recommended. Context.openFileInput() and Context.openFileOutput() make sure you stay in your applications storage context on the device, and that all of your files get
deleted when your app gets uninstalled.
With the standard java.io.File this is the function I have created, and works correctly:
private static final String APP_SD_PATH = "/Android/data/com.pkg.myPackage";
...
public boolean fileExistsInSD(String sFileName){
String sFolder = Environment.getExternalStorageDirectory().toString() +
APP_SD_PATH + "/Myfolder";
String sFile=sFolder+"/"+sFileName;
java.io.File file = new java.io.File(sFile);
return file.exists();
}
why dont you just catch the FileNotFound exception and take that as the file not being present.
If you want to ensure a file exists (i.e. if it doesn't exist create a new one, if it does then don't erase it) then use File.createNewFile:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile()
e.g.
{
String pathName = <file path name>
File file = new File (pathName);
Uri pathURI = Uri.fromFile (file);
boolean created;
String mIOException = "";
String mSecException = "";
try
{
created = file.createNewFile();
if (created)
{
ctxt.sendBroadcast (new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, pathURI));
}
}
catch (IOException ioex)
{
mIOException = ioex.getMessage();
}
catch (SecurityException sex)
{
mSecException = sex.getMessage();
}
}
If you want to open a file in any case (i.e. if it doesn't exist create a new one, if it does append to the old one) you can use this, no testing necessary:
public static void write_custom_log(String message){
File root = Environment.getExternalStorageDirectory();
try{
BufferedWriter fw = new BufferedWriter(new FileWriter(new File("/mnt/sdcard/tjb_tests/tjb_log_file.txt"),true));
if (root.canWrite()){
fw.write(message);
fw.close();
}
} catch (IOException e) {
Log.e("One", "Could not write file " + e.getMessage());
}
}
My suggestion is to check length of the file. if file.length() returns 0 that means file doesn't exist.