How can i edit line 2 in filereader and buffered reader - Java - java

I have this code but when i press the button its edit only the first line in txt file:
String editN = jTextField13.getText();
if (jTextField18.getText().equals("1")) {
try {
String verify, putData;
File file = new File("Name.txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(editN);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while ((verify = br.readLine()) != null) {
if (verify != null) {
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
bw.close();
FileReader fr2 = new FileReader(file);
BufferedReader br2 = new BufferedReader(fr2);
String line1 = br2.readLine();
br2.close();
Worker1.setText("1. " + line1);
EditWorker.setVisible(false);
Workers.setVisible(true);
Workers.pack();
} catch(IOException e) {
e.printStackTrace();
}
}
What I need to add that it will edit second line?
I need to edit something that it will edit the second line in the txt file.

Related

Rewrite a specific line in a txt file

I was trying to rewrite a line that contains student details in a txt file. There will be a list of students' detail in the file, for example:
Name1,10
Name2,20
Name3,30
I tried to rewrite Name2,20 to Name2,13 using a BufferedReader to find the line with Name2. And a BufferedWriter to replace the line with new text, but it turns out the code will write my whole txt file to null.
Here's my code:
String lineText;
String newLine = "Name,age";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
BufferedWriter bw = new BufferedWriter(new FileWriter(path,false));
while ((lineText = br.readLine()) != null){
System.out.println(">" + lineText);
String studentData[] = lineText.split(",");
if(studentData[0].equals(Name2)){
bw.write(newLine);
}
System.out.println(lineText);
}
br.close();
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
Can anyone please tell me how to rewrite a specific line in txt file?
Easiest way is to read the entire file, and store it in a variable. Replacing the line in question while reading the current file.
Something like:
String lineText;
String newLine = "Name,age";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
BufferedWriter bw = new BufferedWriter(new FileWriter(path,false));
String currentFileContents = "";
while ((lineText = br.readLine()) != null){
System.out.println(">" + lineText);
String studentData[] = lineText.split(",");
if(studentData[0].equals("Name2")){
currentFileContents += newLine;
} else {
currentFileContents += lineText;
}
}
bw.write(currentFileContents);
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}

how to get the data from file and set to text Area in vaadin

I have Created One project.Buta i get data in console i want set data to textarea
File[] F=File.listFiles();
for (File File1:F) {
FileInputStream fstream = null;
String strLine ;
try {
fstream = new FileInputStream(File1);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
while ((strLine = br.readLine()) != null)
System.out.println (strLine);
String str=strLine;
final TextArea txt=new TextArea(str);
layout.addComponents(txt);
//br.close();
} catch (IOException e) {
e.printStackTrace();
}
You must accumulate the read lines, so you can then later on add it to the text area.
You might consider what to do with line breaks, currently they just get sorted out of the final string/text.
for (File File1:F)
{
FileInputStream fstream = null;
String strLine;
StringBuilder sb= new StringBuilder();
try
{
fstream = new FileInputStream(File1);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
while ((strLine = br.readLine()) != null)
{
System.out.println (strLine);
sb.append(str);
}
final TextArea txt=new TextArea(sb.toString());
layout.addComponents(txt);
//br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}

Can't write all list to the file

I have an ArrayList list of some lines from text file. I am trying to find these lines in a text file, if I find it I want to write it to another text file and delete it from the original file.
I wrote a code for that, it is working but not for the whole list, sometimes take one line and sometimes take more. and give me this message:
1 R101 100850 0
Exception caught : java.io.IOException: Stream closed
static void moveLines(ArrayList posList, int topic) {
//=======================To read lines=======
File inputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\TestData\\topic\\" + "Test" + topic + ".txt");
File outputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\TestData\\topic\\" + "Training" + topic + ".txt");
try {
FileReader fr = new FileReader(inputFile);
BufferedReader br = new BufferedReader(fr);
FileWriter fr1 = new FileWriter(outputFile);
BufferedWriter writer = new BufferedWriter(fr1);
String line;
int count = 1;
int z = 1;
while ((line = br.readLine()) != null) {
// System.out.println(z++ + ": ");
String subLine = line.substring(5, line.length() - 2);
// System.out.println(subLine);
if (posList.contains(subLine)) {
System.out.println(count++ + " " + line);
fr1.write(line);
fr1.write("\n");
fr1.flush();
fr.close();
removeLineFromFile(inputFile.getAbsolutePath(), line);
}
}
br.close();
fr1.close();
writer.close();
} catch (Exception e) {
System.out.println("Exception caught : " + e);
}
}
static void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
//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(file));
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(lineToRemove)) {
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();
}
}
Can someone help me please?
String subLine = line.substring(5, line.length() - 2);
You are hard coding to take substring from index 5.
What happens when the length of line is less than 5? have a check if the line's length is less than 5 and only then proceed.
Also why are catching with 'Exception' ? try catching with a lower level exception like ArrayIndexOutOfBoundsException etc.
Thank you all for your help.
I figure out the problem, it was because I delete the file and create it again from temp file. in that case I lose the pointer to the file.
This is the code after I fix it if someone interested.
static void moveLines(ArrayList posList, int topic) {
//=======================To read lines=======
File inputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\Data1\\topic\\" + "Test" + topic + ".txt");
File outputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\Data1\\topic\\" + "Training" + topic + ".txt");
try {
FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(outputFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
String subLine = line.substring(5, line.length() - 2);
if (posList.contains(subLine)) {
System.out.println(count++ + " " + line);
bufferedReader.close();
fileReader.close();
bufferedWriter.write(line+"\n");
bufferedWriter.flush();
bufferedReader = removeLineFromFile(inputFile.getAbsolutePath(), line);
}
}
bufferedWriter.close();
fileWriter.close();
bufferedReader.close();
fileReader.close();
} catch (Exception e) {
System.out.println("Exception caught : " + e);
}
}
static BufferedReader removeLineFromFile(String file, String lineToRemove) {
BufferedReader bufferedReader = null;
try {
File inFile = new File(file);
//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(file));
BufferedWriter bw = new BufferedWriter(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(lineToRemove)) {
bw.write(line+"\n");
bw.flush();
}
}
bw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return null;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile)) {
System.out.println("Could not rename file");
}
FileReader fileReader = new FileReader(inFile);
bufferedReader = new BufferedReader(fileReader);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return bufferedReader;
}

Buffered Reader Change

Hi I want to replace the BufferedReader in the piece of code with scanner?? I wrote this code but then realized that we're not allowed use bufferedreader. But Havent a clue how to even go about,
public static void Option1Method() throws IOException
{
FileWriter aFileWriter = new FileWriter("wordlist.txt", true);
PrintWriter out = new PrintWriter(aFileWriter);
String word = JOptionPane.showInputDialog(null, "Enter a word");
out.println(word);
out.close();
aFileWriter.close();
String inputFile = "wordlist.txt";
String outputFile = "wordlist.txt";
FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String inputLine;
List<String> lineList = new ArrayList<String>();
while ((inputLine = bufferedReader.readLine()) != null) {
lineList.add(inputLine);
}
fileReader.close();
Collections.sort(lineList);
FileWriter fileWriter = new FileWriter(outputFile);
PrintWriter out1 = new PrintWriter(fileWriter);
for (String outputLine : lineList) {
out1.println(outputLine);
}
out1.flush();
out1.close();
fileWriter.close();
}
Take a look at the definitions for hasNextLine and nextLine in the Scanner class.
Although new Scanner(fileReader) works, you could rather pass the file name directly into the Scanner's constructor.

BufferedReader Replacement

This method is used to add words to a txt file and then sort them but I am not allowed use the Buffered Reader Function in my course. Is it possible to use Scanner to do this
public static void Option1Method() throws IOException
{
FileWriter aFileWriter = new FileWriter("wordlist.txt", true);
PrintWriter out = new PrintWriter(aFileWriter);
String word = JOptionPane.showInputDialog(null, "Enter a word");
out.println(word);
out.close();
aFileWriter.close();
String inputFile = "wordlist.txt";
String outputFile = "wordlist.txt";
FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String inputLine;
List<String> lineList = new ArrayList<String>();
while ((inputLine = bufferedReader.readLine()) != null) {
lineList.add(inputLine);
}
fileReader.close();
Collections.sort(lineList);
FileWriter fileWriter = new FileWriter(outputFile);
PrintWriter out1 = new PrintWriter(fileWriter);
for (String outputLine : lineList) {
out1.println(outputLine);
}
out1.flush();
out1.close();
fileWriter.close();
}
Sure, you can. Here are equivalent codes using BufferedReader and Scanner
public void bufferedReaderVersion() throws Exception{
File f = new File("filePath");
Reader reader = new FileReader(f);
BufferedReader bufferedReader = new BufferedReader(reader);
String line = null;
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
bufferedReader.close();
reader.close();
}
public void scannerVersion() throws Exception{
File f = new File("filePath");
Scanner sc = new Scanner(f);
while(sc.hasNext()){
System.out.println(sc.nextLine());
}
sc.close();
}

Categories

Resources