Replace Line in File - java

I have a text file which I have a BufferedReader read from.
String sCurrentLine;
File myFile = new File("/sdcard/file.txt");
BufferedReader buf = new BufferedReader(new FileReader(myFile));
while ((sCurrentLine = buf.readLine()) != null) {
}
What I want to do is read a specific line and then replace it with something else whilst leaving the rest of the file alone. How should I do this?

Create a temporary file
Read through the file file.txt, write the output to the temporary file making the replacement as necessary
Close the file
Delete/backup the original file
Rename the temporary file to the original file

Related

GZIP Input Stream strips trailing commas in Java

I was trying to read a CSV file in Java. It had been compressed by GZIP and I used the inbuilt GZIPInputStream to read the CSV file. The piece of code being used to read the file was as follows:
BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("xyz.csv.gz"))));
Some days later, I compressed 4 files using the zip format and they were in a folder named xyz.zip. Note: The 4 files were not individually compressed. This files was being read in the following manner:
InputStream is = getClass().getResourceAsStream("xyz.zip");
ZipInputStream zipIs = new ZipInputStream(is);
ZipEntry ze = null;
while ((ze = zipIs.getNextEntry()) != null) {
String zipEntryFilename = ze.getName();
BufferedReader br = new BufferedReader(new InputStreamReader(zipIs));
while ((line = br.readLine()) != null) {
//assume that a csv file is being read.
//In this format, trailing commas are not removed.
}
One difference I discovered in these two methods was that GZIP stripped trailing commas in the csv files, while the same did not happen in the other case.
The two pieces of code given above show how I am using the InputStream to read the files of my interest.
What is the reason behind this behavior? Is this a bug?

How to update a text file based on values within it

I want to edit certain values(a row values) of a csv file based on a specific value of that row (an id). I am able to read and write (append) the values in it but cannot figure out how to edit and delete them.
Here is a small fragment of code for what I am doing for reading the file and appending values:
FileWriter writer = new FileWriter("file.csv", true);
try {
FileInputStream fstream = new FileInputStream("file.csv");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] fields = strLine.split(",");
if (fields[1].equals("value") {
fields[1] = "different value";
}
writer.append(fields);
}
catch(...)
}
But I can't work out how to write the values back into the same spot in the file.
Unfortunately you can't open a single file for both reading and writing at the same time. You need to read the file and close it before opening it for writing.
The potential solutions are:
Write the output to a different file and then replace the original when complete
Keep all the output in internal variables then, once you've finished reading, close the file and reopen it for writing.

Java read file and send in the server

I need to read contents of a file as a server, and then send the read data file, for the client so the client print it out on the Client terminal.
The problem is that I can't find a way or method to read a txt file from the current directory which my java file and txt file are existed.
Please help me.
There are many ways to read text file or file in java. It depend on you to that in which format you need to pass your file content to client side.
Here are some method to reading file in java.
1. Using BufferedReader class
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
String curLine = line;
//Process line
}
2.Using Apache Common IOUtils with the class IOUtils.toString() method.
FileInputStream inputStream = new FileInputStream("FILEPATH/FILENAME");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
3.Using the Scanner class in Java and the FileReader
Scanner in = new Scanner(new FileReader("FILENAME/FILEPATH"));
while (scanner.hasNextLine()){
//process each line in some way
String line = scanner.nextLine();
}
Scanner has several methods for reading in strings, numbers, etc...
4.In JAVA 7 this is the best way to simply read a textfile
new String(Files.readAllBytes(...))
or Files.readAllLines(...)
Path path = Paths.get("FILENAME");
List<String> allLines = Files.readAllLines(path, ENCODING);
Please refer this link for more onfomation.
You can use BufferedReader to read from a txt file.
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
here fileName is a string that contain your absolute file name.
eg : fileName = "C:\temp\test.txt";
You can read file by using BufferedReader.
File file=new File("filepath");
BufferedReader br=new BufferedReader(new FileReader(file)); //Here you create an object of bufferedreader which file read through filereader
String data=br.readLine();
while(data!=null)
{
System.out.println(data); // Writing in the console
data=br.readLine();
}
This will taking input from file and giving output to console.If you want it write in other file then use BufferedWriter.
File out=new File("outputfilepath");
BufferedWriter bw=new BufferedWriter(new FileWriter(out));
simply us bw.write() instead of System.out.println();.

Reading a json file from local path by bufferedReader to construct a html file

I am using following code to write json to my local path which i get from my html page.Again I have to construct a html page by reading content from the saved local json file.For this I have to read this saved file from local which is plain text and give as input to java file. I got confused whether to use Buffered Reader or BufferedInputStream to read that file from local path.Please help me.
java.io.BufferedWriter jsonOut = new java.io.BufferedWriter(
new java.io.OutputStreamWriter(
new java.io.FileOutputStream(uploadDir +
_req.getParameter("filename")), "ISO-8859-1"));
BufferedReader for text.
Reason: http://tutorials.jenkov.com/java-io/bufferedreader.html
You can use BufferedReader for text but you should ensure to use the proper charset in your case (otherwise it defaults to the platform charset)
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(myFile),"ISO-8859-1"));
To read a file you can use the following code
File f = new File("your json file");
BufferedReader buf = new BufferedReader(new FileReader(f));
String line = null;
while ((line = buf.readLine()) != null) {
System.out.println("json file line " + line);
// do your changes
}

How to delete a specific string in a text file?

How can I delete a specific string in a text file?
Locate the file.
File file = new File("/path/to/file.txt");
Create a temporary file (otherwise you've to read everything into Java's memory first).
File temp = File.createTempFile("file", ".txt", file.getParentFile());
Determine the charset.
String charset = "UTF-8";
Determine the string you'd like to delete.
String delete = "foo";
Open the file for reading.
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
Open the temp file for writing.
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
Read the file line by line.
for (String line; (line = reader.readLine()) != null;) {
// ...
}
Delete the string from the line.
line = line.replace(delete, "");
Write it to temp file.
writer.println(line);
Close the reader and writer (preferably in the finally block).
reader.close();
writer.close();
Delete the file.
file.delete();
Rename the temp file.
temp.renameTo(file);
See also:
The Java Tutorials - Lesson: basic I/O

Categories

Resources