I have a method called "add" which takes a string as an argument and uses the bufferedwriter to write it to the file. Once this is done, the bufferedwriter is flushed.
In another method "read", I loop through the lines in the file, but the lines are null (hence I cannot print them).
When I call "read" inside "add", I can print the lines nonetheless.
public String add(String data) throws IOException{
this.bufferedWriter.write(data);
this.bufferedWriter.flush();
//this.read(data);
logger.info("written " +data);
return data;
}
public String read(String key) throws IOException{
logger.info("start reading ...: ");
String line = this.bufferedReader.readLine();
while (line!= null) {
logger.info("loop start reading ...: "+line);
if(line.split(" ").equals(key)) {
logger.info("reading line: "+line);
return line;
}
line = this.bufferedReader.readLine();
}
return "F"; // indicates the key is not in the storage
}
This is the full code:
public class FileManager {
Path dataDir;
File f;
FileReader fileReader;
BufferedReader bufferedReader;
FileWriter fileWriter;
BufferedWriter bufferedWriter;
public static Logger logger = Logger.getLogger(FileManager.class.getName());
public FileManager(Path dataDir) throws IOException {
logger.info("in file manager: ");
this.dataDir = dataDir;
String dirName = dataDir.toString();
String fileName = "fifo2.txt";
File dir = new File (dirName);
dir.mkdirs();
f = new File (dir, fileName);
logger.info("file established at "+f.getAbsolutePath());
if(!f.exists()){
logger.info("file not there so create new one ");
f.createNewFile();
logger.info("file created!!! ");
}else{
logger.info("file already exists");
System.out.println("File already exists");
}
logger.info("file stage complete");
this.fileReader = new FileReader(f);
this.bufferedReader = new BufferedReader(fileReader);
this.fileWriter = new FileWriter(f, true);
this.bufferedWriter = new BufferedWriter(fileWriter);
}
public String add(String data) throws IOException{
this.bufferedWriter.write(data);
this.bufferedWriter.flush();
//this.read(data);
logger.info("written " +data);
return data;
}
public String read(String key) throws IOException{
logger.info("start reading ...: ");
String line = this.bufferedReader.readLine();
while (line!= null) {
logger.info("loop start reading ...: "+line);
if(line.split(" ").equals(key)) {
logger.info("reading line: "+line);
return line;
}
line = this.bufferedReader.readLine();
}
return "F"; // indicates the key is not in the storage
}
public String delete(String key) throws IOException{
logger.info("Entering deletion in file storage");
String line;
while ((line = this.bufferedReader.readLine()) != null) {
if(line.split(" ").equals(key)) {
line = "DELETED";
logger.info("del_reading line: "+line);
bufferedWriter.write(line);
}
line = this.bufferedReader.readLine();
}
return "F"; // indicates the key to be deleted is not in the storage
}
}
What you should try to do is to create a new instance of BufferedReader/Writer each time you do a read/write operation with the file. Make sure to flush and close after each use.
Related
I can't find out how I can remove through the console with surname a line from a text file. I have to write a surname out in the console and delete all records with this surname.
my file.txt
name surname data 11.11.1111
name1 surnama1 data1 12.12.2010
My Person class:
public class Person implements Serializable, Comparable<Person> {
public String name;
public String surname;
public String secondName;
public String age;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age.equals(person.age) &&
Objects.equals(name, person.name) &&
surname.equals(person.surname) && secondName.equals(person.secondName);
}
getters,setters,toString , constructor here...
public static Person parseRemove(String string) {
String[] parts = string.split(" ");
return new Person(parts[0], parts[1], parts[2], parts[3]);
}
compare here
conparebySurname here
my Remove method, but its does not work well, and I don't know what I should fix here:
public static Boolean removeSurname() throws IOException {
File file;
String line;
Scanner in = new Scanner(System.in);
Set<Person> res = new TreeSet<>();
System.out.print("from which file: ");
line = in.nextLine();
System.out.print("which surname u need to delete ");
String lineToRemove;
String inLine = "";
lineToRemove = in.nextLine();
try {
file = new File(in.nextLine());
System.out.println();
} catch (NullPointerException n) {
System.err.println("no file");
return false;
}
FileInputStream fis = new FileInputStream(line + ".txt");
BufferedWriter bufferWriter = new BufferedWriter(new FileWriter(line + ".txt", true));
InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(isr);
String strInfo;
byte[] buffer = new byte[1024];
while ((strInfo = reader.readLine()) != null) {
String[] arrInfo = strInfo.split(" ");
res.add(new Person(arrInfo[0], arrInfo[1], arrInfo[2], arrInfo[3]));
bufferWriter.write(strInfo) ;
if(lineToRemove.equals(strInfo)){
res.remove(strInfo); //???
// bufferWriter.newLine();
bufferWriter.flush();
}
}
fis.close();
reader.close();
bufferWriter.close();
return true;
}
You can try this code:
public class Main {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
String surname = in.nextLine();
FileInputStream fileInputStream = new FileInputStream("data.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String strInfo;
List<String> records = new ArrayList<>();
while ((strInfo = bufferedReader.readLine()) != null) {
String[] person = strInfo.split(" ");
String personSurname = person[1];
if (!surname.equals(personSurname))
records.add(strInfo);
}
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("data.txt"));
for (String record: records) {
bufferedWriter.write(record + "\n");
}
bufferedWriter.flush();
}
}
PS: You should create bufferedWriter only after you read all the data from the file. When you instantiate bufferedWriter object, it will make your file empty.
I need to replace multiple words in txt file using java. This program only replacing the only one word, in whole file.
import java.io.*;
public class MultiReplace
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
String newtext = oldtext.replaceAll("india", "freedom");
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Try this:
import java.io.*;
public class MultiReplace
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
// Replace in the line and append
line = line.replaceAll("india", "freedom");
oldtext += line + "\r\n";
}
reader.close();
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);
writer.flush();
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Refer this to understand why your version is not working.
Your solution is correct!! I ran your program as is and it is able to replace all the india with freedom in the text file
I some code that takes a file called wonder1.txt and writes the date in that file to another file. Lets say I have more files like wonder2.txt, wonder3.txt, wonder4.txt. How do I write the rest in the same file.
import java.io.*;
import java.util.*;
import java.lang.*;
public class alice {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = ("/Users/DAndre/Desktop/Alice/wonder1.txt");
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "/Users/DAndre/Desktop/Alice/new1.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}
If you have list of files, then you can loop over them one by one. Your current code moves inside the loop.
The easier way would be to put all the files in one folder and read from it.
Something like this :
File folder = new File("/Users/DAndre/Desktop/Alice");
for (final File fileEntry : folder.listFiles()) {
String fileName = fileEntry.getAbsolutePath();
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
Ok, forgive my beginner-ness and please tell me how I can output my text from "before.txt" into a fresh new file called "after". Obviously I have altered the text along the way to make it lower-case and eliminate non alphabetic characters.
import java.io.*;
public class TextReader {
public void openFile() throws IOException {
try {
// Read in the file
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine = br.readLine();
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
br.close(); // Close br to prevent resource leak
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}
public void writeFile() throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
output.write("before.txt");
output.close();
}
}
What about this
public void openFile() throws IOException {
try {
// Read in the file
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine = br.readLine();
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
br.close(); // Close br to prevent resource leak
writeFile(currentLine);
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}
public void writeFile(String text) throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
output.write(text);
output.close();
}
}
Let me guess, is this a school assignment?
Try this:
public void ReadAndWrite() throws IOException {
try {
// Read in the file
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine;
while((currentLine = br.readLine()) != NULL){
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
output.write(currentLine);
}
br.close(); // Close br to prevent resource leak
output.close();
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}
how can i
write data to file without erasing the old content
Use new FileOutputStream(file, true). This will open file in "append" mode which will append all data written to the stream to the end of that file.
You mean "how do you append to a file"? Look for an [append-version of a constructor][1] of your File writing class, e.g.:
public FileWriter(String fileName,
boolean append)
throws IOException
Use this constructor and pass true for the append parameter.
[1]: http://download.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
if you used the new one in Java 7, you can use this way
try (BufferedWriter writer = Files.newBufferedWriter(outFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND))
in this code i use append (true) but my old date erase and new data overwrite on it please give me solution on it
public class FileOperation {
private static FileReader fileReader;
private static FileWriter fileWriter;
private static BufferedReader bufferedReader;
private static BufferedWriter bufferedWriter;
private static PrintWriter writer;
public static File file = new File("C:\\StudentInfo\\com\\education\\students\\file\\managing\\v1_0\\Student.txt");
public FileOperation() throws IOException {
fileReader = new FileReader(file);
fileWriter = new FileWriter(file, true);
bufferedReader = new BufferedReader(fileReader);
bufferedWriter = new BufferedWriter(fileWriter);
// FileOperation fo =new FileOperation();
}
public boolean enrollSudnents(ArrayList<Student> studentList) {
try {
writer = new PrintWriter(file);
writer.print("");
bufferedWriter = new BufferedWriter(new FileWriter(file));
for (Student s : studentList) {
String nameNumberString = String.valueOf(s.getRoll() + "!" + s.getFirstName() + "!" + s.getLastName()
+ "!" + s.getClassName() + "!" + s.getAddress() + "\n");
bufferedWriter.write(nameNumberString);
}
return true;
} catch (Exception e) {
return false;
} finally {
try {
bufferedWriter.close();
fileWriter.close();
} catch (Exception e) {
// logger.info("Exception Found In Adding data");
}
}
}