Files java replacing characters - java

I have to check a text doc whether it exists or not and then i have to replace a letter in that say a to o. I have done the first part how to replace char
class FDExists{
public static void main(String args[]){
File file=new File("trial.java");
boolean exists = file.exists();
if (!exists) {
System.out.println("the file or directory you are searching does not exist : " + exists);
}else{
System.out.println("the file or directory you are searching does exist : " + exists);
}
}
}
This i have done

You cannot do that in one line of code.
You have to read the file (with an InputStream), modify the content, and write it in the file (with an OutputStream).
Example code. I omitted try/catch/finally blocks for a better comprehension of the algorithm but in a real code, you have to add theses blocks with a correct gestion of resources liberation. You can also replace "\n" by the system line separator, and replace "a" and "o" by parameters.
public void replaceInFile(File file) throws IOException {
File tempFile = File.createTempFile("buffer", ".tmp");
FileWriter fw = new FileWriter(tempFile);
Reader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while(br.ready()) {
fw.write(br.readLine().replaceAll("a", "o") + "\n");
}
fw.close();
br.close();
fr.close();
// Finally replace the original file.
tempFile.renameTo(file);
}

Related

FileReaders readLine return always null JAVA

Writing a program in java I'm trying to read the content of a file which is treated as a storage. I have a function to modify the amount of an object in the store, which is organized with one line per product, where the first word is the prodCode, and the second is the amount of it.
This is the function:
public static void modifyAmount(String prodCode, String newAmount){
try{
File magazzino = new File("Magazzino.txt");
BufferedReader fromFile = new BufferedReader(new FileReader("Magazzino.txt"));
FileWriter toFile = new FileWriter(magazzino);
String oldContent="";
String line;
String lineToReplace = prodCode + " " + amountRequest(prodCode);
String newLine = prodCode + " " + newAmount;
while((line = fromFile.readLine()) != null){
oldContent = oldContent + line + "\n";
System.out.println("leggendo " + line);
}
System.out.println(oldContent);
String newContent = oldContent.replaceAll(lineToReplace, newLine);
toFile.write(newContent);
toFile.close();
fromFile.close();
}catch(IOException e){
e.printStackTrace();
}
}
And the result of it is that it won't enter the while cycle because the first readLine result null, though the file is correctly formatted, the 'amountRequest' function works properly and the input is correct.
Magazzino.txt:
1 12
3 25
4 12
You're probably having trouble because you're trying to read and write the file at the same time, with different file handles. I'd suggest reading the file first, then closing the FileReader, then creating a FileWriter to write to it.
The issue is that before you have read the contents of the file, you are creating an instance of FileWriter which will clear the file.
FileWriter toFile = new FileWriter("Magazzino.txt"); will clear the file
The solution is to just create the instance of FileWriter after you are done reading the file.
public static void modifyAmount(String prodCode, String newAmount){
try{
File magazzino = new File("Magazzino.txt");
BufferedReader fromFile = new BufferedReader(new FileReader("Magazzino.txt"));
String oldContent="";
String line;
String lineToReplace = prodCode + " " + amountRequest(prodCode);
String newLine = prodCode + " " + newAmount;
while((line = fromFile.readLine()) != null){
oldContent = oldContent + line + "\n";
System.out.println("leggendo " + line);
}
fromFile.close();
System.out.println(oldContent);
String newContent = oldContent.replaceAll(lineToReplace, newLine);
FileWriter toFile = new FileWriter(magazzino);
toFile.write(newContent);
toFile.close();
}catch(IOException e){
e.printStackTrace();
}
}
You open a file twice, simultaneously for reading and writing.
As soon as you do this line,
FileWriter toFile = new FileWriter(magazzino);
your file is erased. Check it yourself.
Actually, with this line you are creating a new empty file for writing instead of the old one.
I'd suggest read file, then close, then write.
You can also try to pen file for append : new FileWriter("filename.txt", true);
This will not erase old file, allowing you to read it. But the new data will be appended to the end, though.
If you want to use you file as a state or storage, I'd suggest to look at sqlite: https://www.sqlite.org/index.html

Reading a file in a directory in java and storing its offset in the directory

I want to be able to read files from a directory in java without the worry of getting an out of memory exception because files.listfiles() and files.list() can only hold so much. I also want to know if there is a way to store the offset of the file in the directory so I can store that number and not have to iterate through the directory again to find it, is this possible?
Right now I'm using Jaime Hablutzel's answer from another question to go through the directory but wondering if I can store the file offset in the directory to go directly to it next time.
My thought was to store the filenames in a text file then store a count to record the number of characters until each new line was encountered which is another filename then use the RandomAccessFile seek() method to go directory to that line from the saved count.
How to list 2 million files in a directory in java
Okay I solved my problem on what I wanted to do. I created an offset to each file I stored in a textfile by taking the length + 1 of each filename and adding it to the offset then writing it to a file.
public static void readOffsets()
{
try {
File file = new File("indexFile.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("indexFile2.txt");
PrintWriter pw = new PrintWriter(fw);
String line;
int offset = 0;
pw.write(offset + "\n");
while((line = br.readLine()) != null)
{
int length = line.length();
offset += length + 1;
pw.write(offset + "\n");
}
pw.close();
br.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
Then when seeking the offset using the randomaccessfile I would get the correct filename.
public static void seekOffset()
{
try {
RandomAccessFile file = new RandomAccessFile("IndexFile.txt", "r");
file.seek(693);
System.out.println(file.readLine());
}
catch(IOException ioe)
{
}
}

Converting a .java file to a .txt document

I am trying to figure out how to load a .java doc and out put it into a text document...
What needs to be done:
Write a program that opens a Java source file, adds line numbers, and
saves the result in a new file. Line numbers are numbers which
indicate the different lines of a source file, they are useful when
trying to draw someone's attention to a particular line (e.g.,
"there's a bug on line 4"). Your program should prompt the user to
enter a filename, open it, and then save each line to an output fix
with the line numbers prepended to the beginning of each line.
Afterward, display the name of the output file. The name of the output
file should based on the input file with the '.' replaced by a '_',
and ".txt" added to the end. (Hint: if you are using a PrintWriter
object called pw to save the text file, then the line
"pw.printf("%03d", x);" will display an integer x padded to three
digits with leading zeros.)
The text.java needs to output into the text document with numbered lines such as:
001 public class dogHouse {
002 public static void main (String[] args) {
003 and so on...
004
import java.io.*;
public class dogHouse {
public static void main(String [] args) throws IOException {
// The name of the file to open.
String fileName = "test.java";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
// The name of the file to open.
finally {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
// Note that write() does not automatically
// append a newline character.
bufferedWriter.write("Hello there,");
// Always close files.
bufferedWriter.close();
}
}
}
You need to print and count the line(s) as you read them. You also need to differentiate between your output file and your input file. And, I would prefer to use try-with-resources Statements. Something like,
String fileName = "test.java";
String outputFileName = String.format("%s.txt", fileName.replace('.', '_'));
try (BufferedReader br = new BufferedReader(new FileReader(fileName));
PrintWriter pw = new PrintWriter(new FileWriter(outputFileName))) {
int count = 1;
String line;
while ((line = br.readLine()) != null) {
pw.printf("%03d %s%n", count, line);
count++;
}
} catch (Exception e) {
e.printStackTrace();
}

Why is my code giving IOException (System could not find the file specified)? [duplicate]

This question already has answers here:
System not able to find the specified file
(2 answers)
Closed 7 years ago.
public static void update(String fileName, String idType, String id, String updatedData[] ) throws Exception{
char fileOutput[];
String wholeData;
String tkn, idtp, idf;
File myFileU = null;
File tempFile = null;
FileReader finU = null;
FileWriter fwU = null;
Scanner frU = null;
try{
finU = new FileReader(myFileU = new File("\\" +fileName + ".txt"));
fileOutput = new char[(int) myFileU.length()];
finU.read(fileOutput);
finU.close();
//System.out.println(myFileU.getCanonicalPath());
tempFile = new File("temp.txt");
tempFile.createNewFile();
fwU = new FileWriter(myFileU, false);
wholeData = new String(fileOutput);
frU = new Scanner(wholeData);
frU.useDelimiter(";");
while(frU.hasNext()){
idtp = frU.next();
idf = frU.next();
if(idtp.equals(idType) && idf.equals(id)){
fwU.write( ";" + idType + ";" + id);
for(int i=0; i< updatedData.length; i++){
fwU.write(";" + updatedData[i]);
}
fwU.write(";" + System.lineSeparator());
frU.nextLine();
}
if(!idf.equals(id))
fwU.write(";" + idtp + ";" + idf);
tkn = frU.nextLine();
fwU.write(tkn);
fwU.write(System.lineSeparator());
if(idf.equals(autoSerial(fileName, idType)))
break;
}
fwU.flush();
fwU.close();
}
catch(IOException e){
System.out.println("error in opening the file U " + e);
}
finally{
}
}
The above method is meant to overwrite the file it is reading from. What it is supposed to do is read from the file, replace the record specified by the user with updated data and overwrite the file with updated data, but it doesn't overwrite the file instead appends the updated record at the end of the file and gives (though if I save the data to a separate file it saves the updated data correctly to it):
java.io.FileNotFoundException: \Schedules.txt (The system cannot find the file specified)
While the file is there and it has read data from it too? Any clue? I'm new to Java!
Your issue is clearly with opening the file using Java. You seem to be getting confused with file path. Following are examples of how you open a file using different locations, etc.
Let's assume your file is named abc.txt and is located in C:\ drive under test_stackoverflow directory then you your path would be as shown below:
FileReader reader = new FileReader(new File("C:\\test_stackoverflow\\abc.txt"));
Notice the double slashes, that is how you skip a slash.
If your file is in the same directory as your java class then the path is as shown below without any slashes
FileReader reader = new FileReader(new File("test.txt"));
Let's assume that the file that you wish to read is one folder above (src) where your java class is then
FileReader reader = new FileReader(new File("src\\test.txt"));
If you are using OSX then you can do something in the following lines
FileReader reader = new FileReader(new File("/Users/Raf/Desktop/abc.txt"));

How to Delete Line in PrintWriter

I am writing a program in Java that writes several lines of information into a CSV file. I want to delete the last line of CSV file, as it is not needed. How would I do this, as the CSV file is created by a PrintWriter, and I don't believe the append method could do this.
The extra line is written because the loop continues for one extra line. This portion of the code is as follows:
public static void obtainInformation() throws IOException {
PrintWriter docketFile = new PrintWriter(new FileWriter("ForclosureCourtDockets"+startingMonth+"_"+startingDay+"_"+startingYear+"-"+endingMonth+"_"+endingDay+"_"+endingYear+".csv", true));
pageContentString = pageContentString.replace('"','*');
int i = 0;
boolean nextDocket = true;
while(nextDocket) {
nextDocket = false;
String propertyCity = "PropertyCity_"+i+"*>";
Pattern propertyCityPattern = Pattern.compile("(?<="+Pattern.quote(propertyCity)+").*?(?=</span>)");
Matcher propertyCityMatcher = propertyCityPattern.matcher(pageContentString);
while (propertyCityMatcher.find()) {
docketFile.write(i+propertyCityMatcher.group().toString()+", ");
nextDocket = true;
}
String descriptionValue = "Description_"+i+"*>";
Pattern descriptionPattern = Pattern.compile("(?<="+Pattern.quote(descriptionValue)+").*?(?=</span>)");
Matcher descriptionMatcher = descriptionPattern.matcher(pageContentString);
while (descriptionMatcher.find()) {
docketFile.write(descriptionMatcher.group().toString()+"\n");
}
i++;
}
docketFile.close();
}
public static void removeLineFromFile() {
try {
File inFile = new File("ForclosureCourtDockets"+startingMonth+"_"+startingDay+"_"+startingYear+"-"+endingMonth+"_"+endingDay+"_"+endingYear+".csv");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader("ForclosureCourtDockets"+startingMonth+"_"+startingDay+"_"+startingYear+"-"+endingMonth+"_"+endingDay+"_"+endingYear+".csv"));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals("^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^")) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
Well, as PrintWriter is just a Writer, which can only append/write/print
So, you can't override the line which you just have written.
Several options you have :
Modify your logic to make sure you don't write the line you want to remove eventually (I think the most logical option)
After writing to file you can use another Reader(say, BufferedReader) to read it again, and then re-write it, without the line you'd like to exclude.
use RandomAccessFile and its seek method to go back and rewrite / remove the line you need.
You could do the following (this is a way to implement kiruwka's first suggestion):
1) write the first line outside of the while loop.
2) Then for each line written within the while loop first output the newline, and only subsequently output the csv line.
This way you will have duplicated code, but you won't end up with a newline at the end of the file. You can also factor out the duplicate code into a helper method.

Categories

Resources