I want to read file content using this code:
String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));
On some systems this file is not present or it's empty. How I catch this exception? I want to print message "No file" when there is no file and there is no value.
The AccessDeniedException can be thrown only when using the new file API. Use an inputStream to open a stream from the source file so that you could catch that exception.
Try with this code :
try
{
final InputStream in = new Files.newInputStream(Path.get("/sys/devices/virtual/dmi/id/chassis_serial"));
} catch (FileNotFoundException ex) {
System.out.print("File not found");
} catch(AccessDeniedException e) {
System.out.print("File access denied");
}
Try to use filter file.canRead()) to avoid any access exceptions.
Create a File object and check if it exists.
If it does then it's safe to convert that file to a byte array and check that the size is greater then 0. If it is convert it to a String. I added some sample code below.
File myFile = new File("/sys/devices/virtual/dmi/id/chassis_serial");
byte[] fileBytes;
String content = "";
if(myFile.exists()) {
fileBytes = File.readAllBytes(myfile.toPath);
if(fileBytes.length > 0) content = new String(fileBytes);
else System.out.println("No file");
else System.out.println("No file");
I know it's not the one liner you were looking for. Another option is just to do
try {
String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));
} catch(Exception e) {
System.out.print("No file exists");
}
Read up on try catch blocks here like MrTux suggested, as well as java Files and java io here.
Related
String pathSrc = "C:\\Users\\me\\Desktop\\somefile.pdf";
//should just check if file is opened by someone else
try
{
FileWriter fw = new FileWriter(pathSrc );
fw.close();
}
catch (IOException e)
{
System.out.println("File was already opened");
return;
}
This code should just check if pdf file is already opened. Instead after that code pdf file is corrupted. and can no longer be opened. Why is that?
Note that FileWriter starts empty everytime you instantiate a FileWriter with the Filename only, and then starts writing the data to the beginning of the file.
There's a second constructor that takes a boolean append flag that starts at the end of the file, appending data to the current file's contents.
This means that your code erases the whole pdf file and then close()s it, saving an empty PDF file, with zero bytes.
This simple change will fix your issue:
String pathSrc = "C:\\Users\\me\\Desktop\\somefile.pdf";
//should just check if file is opened by someone else
try {
FileWriter fw = new FileWriter(pathSrc, true);
fw.close();
}
catch (IOException e) {
System.out.println("File was already opened");
return;
}
I'm having a problem with an assignment from school. I'm meant to output an arraylist of objects to a file, which I can do. But I'm supposed to check if the file exists, and if it does, then to output to that file, and not create a new one.
I've tried putting the FileOutputStream declaration outside of my if statement, but then the file will always exist.
I've also tried creating a new ObjectOutputStream in my first half of the if statement, but I get an IOException about the headers.
How do I write the objects (of class Employee) to a file that already exists?
public void saveEmployeesToFile() {
try {
File employeeFile = new File("CurrentEmployees.emp");
if (employeeFile.exists()) {
System.out.println("File already exists");
} else {
FileOutputStream employeeFileObject = new FileOutputStream(employeeFile);
ObjectOutputStream output = new ObjectOutputStream(employeeFileObject);
for (Employee thisEmp : getEmployees()) {
output.writeObject(thisEmp);
}
System.out.println("Employees successfully saved to new file");
employeeFileObject.close();
output.close();
}
} catch (IOException ioe) {
System.out.println("Error initializing stream");
System.out.println(ioe.getMessage());
}
}
You can leverage the newer NIO package.
Your question is essentially, "how do I create a FileOuputStream for a file that already exists?"
Path employeeFilePath = Paths.get(employeeFile.toURI());
FileOutputStream employeeFileObject;
if (employeeFile.exists()) {
employeeFileObject = Files.newOutputStream(employeeFilePath, StandardOpenOption.TRUNCATE_EXISTING);
}
else {
employeeFileObject = Files.newOutputStream(employeeFilePath, StandardOpenOption.CREATE_NEW);
}
// Proceed to write data
I want to get the filename of the file that do not exist when a file exception occur in my java application so that i can give a short message to the user.
catch (FileNotFoundException e) {
/* what code to put here to get the filename of the file */
}
This should display the non-existing file path:
try {
//access file
} catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
Output, for creating a Scanner with new Scanner(new File("C:/filetest")):
C:\filetest (The system cannot find the file specified)
You cannot grap properly the filename unless you parse the stacktrace in your catch block.
You can either store the filename outside of the try block, i.e.:
String filename = ...
try {
// process file
} catch (FileNotFoundException e) {
String message = String.format("The file % could not be found.", filename);
// Show message to user
}
Or you can check whether the file exists before trying to access it:
File file = new File(filename);
if (!file.exists()) {
// Show error to user.
}
I've been trying to open a text file and and save each line as the contents of an arraylist. Once this has been completed I would like to save it back to a file. I have been running into errors for so long and have tried numerous techniques. I found that for some reason, the files themselves are not being created. It may just be a simple error I'm overlooking but if you could provide any help I will be thankful.
Here's the code:
public void addToFile(){
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations");
root.mkdirs();
File fileName = new File(root, "locationslatitude.txt");
File fileName2 = new File(root, "locationslongitude.txt");
String file = fileName.toString();
String file2 = fileName2.toString();
String theContent = Double.toString(currLatitude);
String theContent2 = Double.toString(currLongitude);
s = new Scanner(file);
while (s.hasNext()){
fileList.add(s.next());
}
s.close();
fileList.add(theContent);
s2 = new Scanner(file2);
while (s2.hasNext()){
fileList2.add(s2.next());
}
s2.close();
fileList2.add(theContent2);
try {//works for latitude file
FileWriter writer = new FileWriter(file);
for(String str: fileList) {
writer.write(str);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
//save the arraylist back to its appropriate file
try {//works for longitude file
FileWriter writer = new FileWriter(file2);
for(String str2: fileList2) {
writer.write(str2);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
}
I believe I found the answer to the problem and I wanted to post it back on here so if anyone else faces the same problem this might help them.
The problem was that it wasn't creating the file. The directory was created using "root.mkdirs();". However, the files were not created and I was trying to read from non-existing files. This is what I believe caused the error. So, in order to fix this problem I altered the code to this:
try{
s = new Scanner(fileName);
while (s.hasNext()){
fileList.add(s.next());
}
s.close();
fileList.add(theContent);
}catch (FileNotFoundException ex){
ex.printStackTrace();
try{
fileName.createNewFile();
}catch (IOException e){
e.printStackTrace();
Toast.makeText(this, "Hit IOException for file one", Toast.LENGTH_SHORT).show();
}
}
try{
s2 = new Scanner(fileName2);
while (s2.hasNext()){
fileList2.add(s2.next());
}
s2.close();
fileList2.add(theContent2);
}catch (FileNotFoundException ex){
ex.printStackTrace();
try{
fileName2.createNewFile();
}catch (IOException e){
e.printStackTrace();
Toast.makeText(this, "Hit IOException for file two", Toast.LENGTH_SHORT).show();
}
}
This was the only piece of code I had to alter. The code which saved back to the file worked. I hope this will be of use to someone and thanks everyone for your help.
This code works in my project. You can use it to save ArrayList contents to text file. Make sure that the directory is created beforehand. Just iterate through your list and use println method to write it to txt file.
FileWriter outFile = new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations/nameoftextfile.txt");
PrintWriter out = new PrintWriter(outFile);
out.println("PRINT LINES WITH ME");
out.print("NOT NECCESSARILY A NEW LINE");
out.close(); // at the very end
Do not forget to catch IOException.
Have you added the following permission in the AndroidManifest.xml?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Check if the file directory etc exists on the device in the first place that you are using
/appName/savedlocations Good chance these do not exist. Wrong name for appName or savedLocations. Check this using some file explorer program. Tell us if it exists. Print out the full path name of
Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations
and see if it really exists. Just download an app for file viewing or I think you can connect to the device via eclipse as well. If you need more info on how to do it let us know. But you should first check the actual error message and report this back.
don't invent your own serialization format. java already has that.
ArrayList<String> files = ...; // whatever
// write the object to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
out.writeObject(files);
out.close();
// read the object back
InputStream is = new FileInputStream("filename.ser");
ObjectInputStream ois = new ObjectInputStream(is);
ArrayList<String> newFiles = = (ArrayList)ois.readObject();
ois.close();
I've got some text in a text file. I want to read it from file (first string - first line in file etc.), do something with it and then write to another text file.
How to do it?
Apache Commons IOUtils:
String contents = FileUtils.readFileToString(file, "UTF-8");
FileUtils.writeStringToFile(file, contents, "UTF-8");
And the best way to find out how that is done internally (in case you are interested) is to look at the source code for these two methods.
java.util.Scanner -> use this for reading content from file(there are lots of other ways as mentioned by others,but i find this one the simplest.)
java.io.PrintWriter -> use for writing into file(other ways also possible,as mentioned above)
You exactly have to do what other folks have mentioned. But here I will be bit detailed and provide you with some code sample.
To open and read the file:
String fileName = "paper.txt"; // file to be opened
try {
Scanner fileData = new Scanner(new File(fileName));
while(fileData.hasNextLine()){
String line = fileData.nextLine();
line = line.trim();
if("".equals(line)){
continue;
} // end if
} // end while
fileData.close(); // close file
} // end try
catch (FileNotFoundException e) {
// Error message
} // end catch
To write to the text file you can use the following code:
boolean fileOpened = true;
try {
PrintWriter toFile = new PrintWriter("paper.txt");
} // end try
catch (FileNotFoundException e) {
fileOpened = false;
// Error Message saying file could not be opened
} // end catch
if(fileOpened){
toFile.println("String to be added to the file");
toFile.close();
} // end if
I hope this will help you out to solve your problem.