I have a network drive at school, I have the ability to read and write to it normally, but when I use java to take an existing text file and try and write to it, I get this exception:
java.io.FileNotFoundException: p:\CompSci_CheckIn_Name.txt (The process cannot access the file because it is being used by another process)
I can read it just fine and all but when I try and write to it, it throws me an exception. I can write to my desktop and read and everything from my desktop but when I try my network drive, it gives up. How could I get around this problem?
Reading
file = new File(directories[i], "CompSci_CheckIn_Name.txt");
readName = new BufferedReader(new FileReader(file));
userName = readName.readLine();
passed = true;
Writing
write = new PrintWriter(file);
write.println(newUser);
write.flush();
userName = newUser;
write.close();
I have already tried a BufferedWriter with no luck, same result.
You should close() BufferedReader and FileReader after using them.
Use a try/finally block and close your Readers in the finally block.
FileReader fr = null;
BufferdReader br = null;
try {
fr = new FileRader(file);
br = new BufferedReader(fr);
// do something..
} finally {
if (br != null) br.close();
if (fr != null) fr.close();
}
Related
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 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.
So I wrote this file reader method that should return a string of everything that is in the file, but it isn't working properly. Writing into the file works perfectly, but this reading method doesn't. What the method does currently is it reads the last string/text added, but it does not read the file from start to finish. 'br' is my bufferedReader, which is declared somewhere else in the same class.
Here's how br is defined:
private static FileInputStream fis;
private static BufferedReader br;
and then in the constructor:
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
Here's the method:
public String readStuff(){
String line = "";
String r = "";
try{
while((line = br.readLine()) != null){
System.out.println(line + " read ");
r+= line;
}
//br.close(); JDK 7 does this automatically apparently
}catch(IOException e){
e.printStackTrace();
System.out.println("Error at readStuff!");
}
return r;
I know I'm making either a logic mistake or some obvious error, I just don't know where.
If you want to read the entire file twice, you will have to close it and open new streams/readers next time.
Those streams/readers should be local to the method, not members, and certainly not static.
Using File and FileReader You can Read / Write File From Dir.
you can get File using File class object
File file = new File("file.txt");
and After Process to read that file
FileReader fr = new FileReader(file);
There are Whole Code to read File...
File file = new File("G:\\Neon\\data.txt");
FileReader fr = new FileReader(file);
String data = "";
while((i = fr.read()) != -1)
{
data = data + (char)i;
}
System.out.println(data);
I am trying to read a variable number of lines from a file, hopefully using InputStream object. What I'm trying to do (in a very general sense) is as follows:
Pass in long maxLines to function
Open InputStream and OutputStream for reading/writing
WHILE (not at the end of read file AND linesWritten < maxLines)
write to file
I know InputStream goes on bytes, not lines, so I'm not sure if that's a good API to use for this. If anyone has any reccomendations on what to look at in terms of a solution (other API's, different algorithm) that's be very helpful.
You can have something like this
BufferedReader br = new BufferedReader(new FileReader("FILE_LOCATION"));
while (br.readLine() != null && linesWritten < maxLines) {
//Your logic goes here
}
Have a look at these:
Buffered Reader and
Buffered Writer
//Read file into String allText
InputSream fis = new FileInputStream("filein.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line, allText = "";
try {
while ((line = br.readLine()) != null) {
allText += (line + System.getProperty("line.separator")); //Track where new lines should be for output
}
} catch(IOException e) {} //Catch any errors
br.close(); //Close reader
//Write allText to new file
BufferedWriter bw = new BufferedWriter(new FileWriter("fileout.txt"));
try {
bw.write(allText);
} catch(IOException e) {} //Catch any errors
bw.close(); //Close writer
I have a text file placed in assets and I want to read one line of it at a time. My problem is that I do not know how to access the file in Activity, and then once I access it, how would I go about only selecting one line?
If keeping the txt file in assets is a bad idea, where should I put it for easier access?
I really appreciate any help!
This is a snippet I use to prepopulate tables in my RSS feed reader. You can use it as a track for your needs.
In res/raw/ I have file feeds.txt. The file is referenced is code like R.raw.feeds.
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.feeds);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 8192);
try {
String line;
while ((line = reader.readLine()) != null) {
//make the use you want with "line"
}
} catch (IOException e) {
Log.e(TAG, "Error loading sample feeds.");
throw new RuntimeException(e);
}
To open assests, you'll need to call
<context>.getAssets().open(<your file>);
<context> is your activity, so if this is in your onCreate, then it would be this. That call returns an inputstream, which you can then handle however you please.
I don't see how it would be a particularly bad idea to keep your text file there, depends on what you're using that text file for.
Try this:
Make a new method for example readMyFile().
It must looks like this:
private String readMyFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder txt = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
txt.append(line);
txt.append("\n");
}
reader.close();
return txt.toString();
Paste it to your code, and use the method (readMyFile([the file what you want to read in assets]).
Hope it helps.