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.
Related
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.
I have a problem of writing the UTF-8 character that cannot be properly read by Excel. When I open the excel, some characters are read as "Ņӊഎ«". I understand this is something to do the UTF BOM. Is there someone who how can help to explain me this?
Here are my codes for writing the CSV.
public class FileWriter {
private static String filenameTemp;
public static boolean creatFile(String name) throws IOException {
boolean flag = false;
filenameTemp = name + "";
System.out.println("write to file: "+filenameTemp);
File filename = new File(filenameTemp);
if (!filename.exists()) {
filename.createNewFile();
flag = true;
}
else {
filename.delete();
filename.createNewFile();
flag = true;
}
return flag;
}
public static boolean writeFile(String newStr) throws IOException {
boolean flag = false;
String filein = newStr + "\r\n";
String temp = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
File file = new File(filenameTemp);
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
for (int j = 1; (temp = br.readLine()) != null; j++) {
buf = buf.append(temp);
buf = buf.append(System.getProperty("line.separator"));
}
buf.append(filein);
fos = new FileOutputStream(file);
byte[] unicode = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
fos.write(unicode);
pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
throw e1;
} finally {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (fis != null) {
fis.close();
}
}
return flag;
}
I was trying to delete a line from a file. I've search on the internet. And i made a method. Here is it.
public void removeLine(BufferedReader br , File f, String Line) throws IOException{
File temp = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
String removeID = Line;
String currentLine;
while((currentLine = br.readLine()) != null){
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(removeID)){
currentLine = "";
}
bw.write(currentLine + System.getProperty("line.separator"));
}
temp.renameTo(f);
bw.close();
br.close();
}
I don't know what is wrong with this method. Could you help me?
Here is where i use this method
delete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt) {
BufferedReader br = null;
try{
String enterID2 = enterID1.getText().trim();
File books = new File("books.txt");
br = new BufferedReader(new FileReader(books));
removeLine(br , books, enterID2);
System.out.println("done");
}catch (NumberFormatException e1) {
System.out.println("This is not a number");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Delete is a JButton. No error recieved.
Try this code:
public static void removeLine(BufferedReader br , File f, String Line) throws IOException{
File temp = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
String removeID = Line;
String currentLine;
while((currentLine = br.readLine()) != null){
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(removeID)){
currentLine = "";
}
bw.write(currentLine + System.getProperty("line.separator"));
}
bw.close();
br.close();
boolean delete = f.delete();
boolean b = temp.renameTo(f);
}
this is my code, im trying to compare two .csv files and match them and save the common pain in another file. How do i do it?
This is the cotnent of item_no.csv file
1
2
3
4
5
This is the content of item_desc.csv file
1,chocolate,100
2,biscuit,20
3,candy,10
4,lollipop,5
5,colddrink,50
6,sandwitch,70
EDIT This is the expected output:
1,chocolate,100
2,biscuit,20
3,candy,10
4,lollipop,5
5,colddrink,50
This is my code:
package fuu;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
public class Demo {
public static void main(String[] args) throws ParseException, IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new FileReader("/home/yotta/eclipse/workspace/Test/WebContent/doc/item_no.csv"));
BufferedReader br1 = new BufferedReader(new FileReader("/home/yotta/eclipse/workspace/Test/WebContent/doc/item_desc.csv"));
String line = null;
String line1 = null;
String line2 = null;
String[] str=null;
String[] str1=null;
try {
while((line = br.readLine())!=null){
str = line.split(",");
System.out.println(str[0]);
}
while((line1 = br1.readLine())!=null){
str1 = line1.split(",");
System.out.println(str1[0]+" "+str1[1]+" "+str1[2]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
You could separate the different steps.
public class Demo {
public static void main(String[] args) throws IOException {
Map<String, String> descMap = new HashMap<>();
String line;
// read all item descriptions
try (BufferedReader br1 = new BufferedReader(new FileReader("item_desc.csv"))) {
while ((line = br1.readLine()) != null) {
int itemNbrSeparator = line.indexOf(',');
String itemNbr = line.substring(0, itemNbrSeparator);
descMap.put(itemNbr, line);
}
}
List<String> matched = new ArrayList<>();
// read the item numbers and store each matched
try (BufferedReader br = new BufferedReader(new FileReader("item_no.csv"))) {
while ((line = br.readLine()) != null) {
if (descMap.containsKey(line)) {
System.out.println(descMap.get(line));
matched.add(descMap.get(line));
}
}
}
// output all matched
Path outFile = Paths.get("item_match.csv");
Files.write(outFile, matched, Charset.defaultCharset(), new LinkOption[0]);
}
}
One way is this
List<String> lines1 = new ArrayList<String>();
while ((line = br.readLine()) != null) {
str = line.split(",");
lines1.add(line);
System.out.println(str[0]);
}
List<String> lines2 = new ArrayList<String>();
while ((line = br1.readLine()) != null) {
str = line.split(",");
System.out.println(str[0]);
if(lines1.contains(str[0])){
lines2.add(line);
}
}
for (String l : lines1) {
System.out.println(l);
}
Error at
bw.write(dataString);
How can i fix this?
dataString cannot be resolved to a variable.
public class test {
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
String dataString = Arrays.toString(dataArray);
String[] client = dataString.split("<::>");
Integer nameId = Arrays.binarySearch(client, "Test");
Integer versId = nameId + 1;
System.out.println(client[nameId] + "\n" + client[versId]);
} catch(FileNotFoundException ex) {
System.out.println("FNFE");
} catch(IOException ex) {
System.out.println("IOE");
}
try{
File file = new File("src/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(dataString);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
DeclaredataString outside of the try and catch block... Thats all. ;) If you declare it inside a loop or in this case your try catch block, its lifecycle is limited to it.
Like this:
String dataString = null;
and inside the try-catch block:
dataString = Arrays.toString(dataArray);
dataString is out of scope in the try block.
Perhaps add dataString as an instance variable at the top of your class.
public class test {
private String dataString = null;
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
dataString = Arrays.toString(dataArray);
...
The dataString variable's scope is limited to the first try-catch block. Change its declaration as following,
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
String dataString = null;
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
dataString = Arrays.toString(dataArray);
String[] client = dataString.split("<::>");
Integer nameId = Arrays.binarySearch(client, "Test");
Integer versId = nameId + 1;
System.out.println(client[nameId] + "\n" + client[versId]);
} catch(FileNotFoundException ex) {
System.out.println("FNFE");
} catch(IOException ex) {
System.out.println("IOE");
}
try{
File file = new File("src/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(dataString);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}