I have written a program in which I am reading a file through the BufferedReader. which file I am reading it may be in .txt format or .csv format.
I want in if file is not available with .txt extension BufferedReader read it with
.csv extension.
I have created a String "FileName" and storing file path on it. and in path variable i have stored file location.
path = "C:\Users\Desktop\folder(1)\"
and I am trying try catch block as follow.
try
{
FileName = path+"abc.txt";
}
catch(Exception e)
{
FileName = path+"abc.csv";
}
BufferedReader BR = new BufferedReader(new FileReader(FileName));
But I am getting java.io.FileNotFoundException.
The exception is thrown in the line BufferedReader SoftwareBundle = new BufferedReader(new FileReader(FileName));
So you need the try/catch-block arround this line:
try
{
FileName = path+"abc.txt";
BufferedReader SoftwareBundle = new BufferedReader(new FileReader(FileName));
}
catch(Exception e)
{
FileName = path+"abc.csv";
BufferedReader SoftwareBundle = new BufferedReader(new FileReader(FileName));
}
This is the ideal structure for the code:
String filename = null;
try (BufferedReader bundle = null) {
try {
filename = path + "abc.txt";
bundle = new BufferedReader(new FileReader(filename));
} catch(FileNotFoundException e) {
filename = path + "abc.csv";
bundle = new BufferedReader(new FileReader(FileName));
}
// use 'bundle' here
} catch(FileNotFoundException e) {
// log that >>neither<< file could be opened.
}
Notes:
Don't catch Exception. If you do that, you will catch all sorts of unexpected stuff, in addition to the exceptions that you are anticipating.
Use a "try with resource" to ensure that that the reader that was opened is always closed.
You need to get the scoping right ... unless you are prepared to duplicate the code that uses the reader.
Even with the "try again" logic, you still need to deal with the case where all of the filenames that you try fail. AND you need to make sure that the "all fail" case doesn't attempt to use the reader.
Related
I tried it this way but it doesn't find the textfile.
try {
FileInputStream fstream = new FileInputStream("textfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
All files are in the same package.
Your text file is inside a the package "trainer" which is inside "src" so when you request it, you must use "src/trainer/textfile.txt". The preceding / denotes the root of the application and is optional if you're not exporting to runnable jars for example.
FileInputStream fstream = new FileInputStream("src/trainer/textfile.txt");
I want to add a functionality in the App where the user can change machine IP scheme (IP, SubnetMask, DefaultGateway) permanently, So I want to do Read/Write operation on the Linux Network Configuration File ("/etc/network/interfaces") using following code.
File file = new File("/etc/network/interfaces");
boolean exists = file.exists();
String line = "";
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try
{
FileReader fr = new FileReader(file.getAbsoluteFile());
//BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(new FileInputStream(file));
if(exists)
{
while(scan.hasNext()) //while((line = br.readLine()) != null)
{
// Any Write operation
}
scan.close(); // br.close
}
}
bw.close();
Problem is that the check on while() loop keeps returning false.
I did some research for any alternative for that which includes using BufferedReader or Scanner to read the file but didn't work. All the following checks just keep returning false.
while(scan.hasNext())
while(scan.hasNextLine())
while((line = br.readLine()) != null)
Although file does exist, it contains its content But every time I try to read it with the above code all file content gets removed and the file gets empty.
Am I missing something? Is there any better alternative? I've also tried reading another file in the same directory which has full permission of read/write/execute for all users but still same result
As I'm trying to open the file to write and read was what causing the issue and loop gets terminated in the beginning. So it turns out that You should not use FileWriter before FileReader for same file. Doing so at the same time causing File reader to read empty file and loop terminates as it gets EndOfFile right at the beginning. Afterwards it closes the file empty hence all its contents are being lost.
Better way was to
First open the file for 'Read' only.
Scan through file line by line & keep a buffer of each line parsed (List in my case).
Add the content you wish to update in the file when you get to your Marker line & update you buffer as well.
Now open the file to 'Write' you updated list on it
Note: This is suitable if the file size is reasonably small to accommodate the file processing time.
File file = new File("/etc/network/interfaces");
boolean exists = file.exists();
Scanner scanner = null;
PrintWriter wirtter = null;
String line = "";
List<String> fileLines = new ArrayList<String>();
if(exists)
{
try {
scanner = new Scanner(new FileInputStream(file));
while(scanner.hasNextLine())
{
line = scanner.nextLine();
fileLines.add(line);
if(line.trim().startsWith("iface eth0 inet static"))
{
while(scanner.hasNextLine())
{
line = scanner.nextLine();
fileLines.add(line);
if(line.trim().startsWith("address"))
{
String updateStr = "\taddress "+ipAddress+"\t";
fileLines.remove(fileLines.size()-1);
fileLines.add(updateStr);
System.out.println("IP add updated");
}
else if(line.trim().startsWith("netmask"))
{
String updateStr = "\tnetmask "+subnetMask+"\t";
fileLines.remove(fileLines.size()-1);
fileLines.add(updateStr);
System.out.println("subnet add updated");
}
else if(line.trim().startsWith("gateway"))
{
String updateStr = "\tgateway "+defaultGateway+"\t";
fileLines.remove(fileLines.size()-1);
fileLines.add(updateStr);
System.out.println("Gatway add updated");
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally{
if(scanner != null)
scanner.close();
}
Now do the Writing Separately. And Also you'd want to restart the networking service
try {
wirtter = new PrintWriter(file);
for (String lineW : fileLines)
wirtter.println(lineW);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally{
if(wirtter != null)
wirtter.close();
}
}
synchronized (p) {
String cmd = "sudo /etc/init.d/networking restart ";
p.exec(cmd);
p.wait(10000);
System.out.println("finishing restart 'Networking:' service");
}
I've tried searching for questions like mine, found alot but non of the answers worked for me.
I'm working with Android studio and trying to open a text file from a java class, but no matter what I do or how I'm trying to open it - I'm getting this error:
"... open failed: ENOENT (No such file or directory)"
As you can see - I also tried two options:
1. creating a "File" class (then at the watches window I tried to invoke - "canRead()" function but getting back "false" value.
2. trying to send the ctor of "FileReader" class the path of my file.
non of them worked.
thanks alot!
public void fillDatabase(){
File file = new File("C:\\fillStops.txt");
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + STOPS_TABLE_NAME);
try {
FileInputStream fileInputStream = new FileInputStream(file);
FileReader fileReader = new FileReader("C:\\fillStops.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
this.addStop(line);
}
fileReader.close();
}
catch (Exception e){
String s = e.getMessage();
}
}
Try this, and place your textfile at the root of your sdcard else change the path for file in the following code.
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
String aDataRow = "";
while ((aDataRow = br.readLine()) != null) {
line+= aDataRow + "\n";
}
Log.d(">>>>>", line);
}
catch (IOException e) {
//You'll need to add proper error handling here
}
Hop it will clear the things for you. :)
P.S
Don't forget to add the <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> permission into your manifest.
I have this method that access a exisitng file, loop thru each line and replace (string to string) a certain line if the condition is met:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
private void UpdateConfig() {
try {
FileInputStream fstream = new FileInputStream("c:\\user\\config.properties");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.contains("FTPDate=2014/07/01 00:59:00")) {
System.out.println("FILE " + strLine);
strLine.replace("FTPDate=2014/07/01 00:59:00", "FTPDate=2014/09/10 00:00:00");
//strLine.replace("((19|20)\\d\\d/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])) ([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])", "2014/09/10 00:00:00");
System.out.println("FILE " + strLine);
}
}
in.close();
} catch (Exception e) {
}
}
In the sysout it seems its being replaced:
FILE FTPDateTejas=2014/07/01 00:59:00
FILE FTPDateTejas=2014/09/10 00:00:00
But when I check the file, the date still stays the same. Am I missing something? anyone knows what I missed out? thank you
When you are doing:
strLine = br.readLine() it loads the next line from the BufferedReader into memory. This means that you have your data on disk and in memory and that those two are not linked to each other in any way. When doing modifications on strLine I believe you have in your code:
strLine = strLine.replace("FTPDate=2014/07/01 00:59:00", "FTPDate=2014/09/10 00:00:00");
As replace doesn't modify the contents of the objects on which it is being called but returns a new String objects (Strings are immutable). So what that does it creates a new object but does not modify your on disk data (as I said, it's not linked to it any more!).
You could think "ok then how do I link those two and override the file in place?". Well Java does provide random file access as described in the doc but the only thing you can do with it is modify characters at a certain position, you cannot insert things in the middle. So what you would have to do is read the rest of your file, make your modification and then append that rest of the file, yes you need to shift things in case your new string with which you are substituting would be shorter/longer than what you are replacing.
That's why an easier solution would be to:
open a new file to write to
write line by line to it (the strings after the replace)
delete the old file and rename the new file
Without copying the file the code would look something like this:
private void UpdateConfig() {
File fstream = new File("c:\\user\\config.properties");
File file = new File("c:\\user\\config.properties-new");
try {
file.createNewFile();
} catch (IOException e) {
// handle
}
try (FileReader in = new FileReader(fstream);
FileWriter fw = new FileWriter(file.getAbsoluteFile())) {
try (BufferedReader br = new BufferedReader(in);
BufferedWriter bw = new BufferedWriter(fw)) {
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.contains("FTPDate=2014/07/01 00:59:00")) {
System.out.println("FILE " + strLine);
strLine = strLine.replace("FTPDate=2014/07/01 00:59:00",
"FTPDate=2014/09/10 00:00:00");
//strLine.replace("((19|20)\\d\\d/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])) ([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])", "2014/09/10 00:00:00");
bw.write(strLine);
System.out.println("FILE " + strLine);
}
}
}
// copy files here
} catch (IOException e) {
// handle
}
}
There might be some logical/syntactic problems as I was writing in in a plain text editor. I modified the code a bit to use Java 7's try-with-resources, which is a cleaner way of closing resources than what you were doing - in your code when an exception would be thrown the stream might not had been closed.
When I read a file from the jar file and want to put it in in a jTextArea, it shows me crypted symbols, not the true content.
What I am doing:
public File loadReadme() {
URL url = Main.class.getResource("/readme.txt");
File file = null;
try {
JarURLConnection connection = (JarURLConnection) url
.openConnection();
file = new File(connection.getJarFileURL().toURI());
if (file.exists()) {
this.readme = file;
System.out.println("all ok!");
}
} catch (Exception e) {
System.out.println("not ok");
}
return file;
}
And then i read the file:
public ArrayList<String> readFileToArray(File file) {
ArrayList<String> array = new ArrayList<String>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(file));
while ((sCurrentLine = br.readLine()) != null) {
String test = sCurrentLine;
array.add(test);
}
} catch (IOException e) {
System.out.println("not diese!");
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
}
}
return array;
}
Now, i put all lines from the ArrayList in the jTextArea, that showes me things like that:
PK����?����^��S?��3��� z_��
%�Q Tl?7��+�;�
�fK� �N��:k�����]�Xk,������U"�����q��\����%�Q#4x�|[���o� S{��:�aG�*s g�'.}���n�X����5��q���hpu�H���W�9���h2��Q����#���#7(�#����F!��~��?����j�?\xA�/�Rr.�v�l�PK�bv�=
The textfiled contains:
SELECTION:
----------
By clicking the CTRL Key and the left mouse button you go in the selection mode.
Now, by moving the mouse, you paint a rectangle on the map.
DOWNLOAD:
---------
By clicking on the download button, you start the download.
The default location for the tiles to download is: <your home>
I am sure that the file exists!
Does anyone know what the problem is? Is my "getResource" correct?
Based on the output, I'm suspecting your code actually reads the JAR file itself (since it starts with PK). Why not use the following code to read the text file:
Main.class.getResourceAsStream("/readme.txt")
That would give you an InputStream to the text file without doing the hassle of opening the JAR file, etc.
You can then pass the InputStream object to the readFileToArray method (instead of the File object) and use
br = new BufferedReader(new InputStreamReader(inputStream));
The rest of your code should not need any change.
This seems to be an encoding problem. FileReader doesn't allow you to specify that. Try using
br = new BufferedReader(new InputStreamReader(new FileInputStream(file), yourEncoding));
You seem to be making far too much work for yourself here. You start by calling getResource, which gives you a URL to the readme.txt entry inside your JAR file, but then you take that URL, determine the JAR file that it is pointing inside, then open that JAR file with a FileInputStream and read the whole JAR file.
You can instead simply call .openStream() on the original URL that getResource returned, and this will give you an InputStream from which you can read the content of readme.txt
br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
(if readme.txt is not encoded in UTF-8 then change that parameter as appropriate)