Let's say I have the following code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class EditFile {
public static void main(String[] args) {
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
bw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( br.readLine() != null ){
verify = br.readLine();
if(verify != null){
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
All I wanted to do was to write something in a text file, in my case "Some text here for a reason". Then to read data from my file, and finally to change my text from my file from "Some text here for a reason" in "Some text there for a reason". I ran the code but all it happens is to write in my file "Some text here for a reason".
I tried to figure out what could be wrong in my code, but unfortunately it was in vain. Any advice or rewrite is highly appreciated from me.
Change your code to that:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class EditFile {
public static void main(String[] args) {
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
bw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (verify=br.readLine()) != null ){ //***editted
//**deleted**verify = br.readLine();**
if(verify != null){ //***edited
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
The Problem is that you are calling br.readLine() twice which is provoking the application to read line1 and then line2 and in your case you have just one line which means that your program read it in the conditional form and when it comes to declaring it to the variable verify, it is stopping because you don't have anymore data to read your file.
I would do it this way:
import java.io.*;
public class EditFile {
public static void main(String[] args) {
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
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();
}catch(IOException e){
e.printStackTrace();
}
}
}
use this code, I used it to remove logs and System.out statements in java file.
just change the matching and replacing string.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
Scanner scan = null;
public void doIt() {
scan = new Scanner(System.in);
while (true) {
try {
System.out
.println("enter qualified file name ex.D:\\shiv\\shiv android all\\Main work space\\Welcomescreen1.java");
String path = scan.nextLine();
File f1 = new File(path);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
int i = 0;
while ((line = br.readLine()) != null) {
if (line.contains("System.out")) {
line = line.replace("System.out", "//");
} else if (line.contains("Log.")) {
line = line.replace("Log", "//");
}
lines.add(i, line);
i++;
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for (int j = 0; j < lines.size(); j++) {
System.out.println(j + "." + lines.get(j));
out.append(lines.get(j));
out.newLine();
}
out.flush();
out.close();
System.out
.println("====================work done===================");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String args[]) {
FileReplace fr = new FileReplace();
fr.doIt();
}
}
import java.io.*;
public class TextFile
{
public static void main(String[] args)
{
try
{
String verify, putData;
File file = new File("G:\\Dairy.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("I am Shah Khalid");
bw.flush();
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();
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println("Shah");
}
}
There is no need to type bw.write(putData);, because it will just print the statement twice.
Whatever you want in a file, just give the correct path of the file and use the above code accordingly.
File file = new File("/tmp/my.txt");
FileWriter fw;
BufferedReader br;
BufferedWriter bw;
boolean no=false;
String line;
String data="";
String lessonPath="my new line";
try {
if(!file.exists()){
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(lessonPath);
bw.flush();
bw.close();
}else{
br = new BufferedReader(new FileReader(file));
while((line =br.readLine()) !=null){
if(!no){
data=line;
no=true;
}else{
data = data+"\n"+line;
}
}
bw = new BufferedWriter(new FileWriter(file));
bw.write(data+"\n"+lessonPath);
bw.flush();
bw.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
Related
How to read from a file strings or numbers with one space between them.
You can just write a class which will read a file and remove the spaces.
package com.example.removespaces
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class RemoveSpacesInFileEx {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt");
String line;
while((line = br.readLine()) != null)
{
line = line.trim();
line=line.replaceAll("\\s+", " ");
fw.write(line);
}
fr.close();
fw.close();
}
}
public void readData() {
File file = new File("file.txt"); //You can put your file name or your file position here
try {
Scanner sc = new Scanner(file);
while(sc.hasNext()) {
System.out.println(sc.nextLine());
} System.out.println();
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
System.out.println("End of the Main");
} //This will read it from a file and print on your console
hello everyone im trying to save data in the notepad but i dont know how to save many lines. with this code i just can save once the data.
package Vista;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class notepad_Data {
public void escribir(String nombreArchivo) {
File f;
f = new File("save_data");
try {
FileWriter w = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(w);
PrintWriter wr = new PrintWriter(bw);
wr.append(nombreArchivo+" ");
bw.close();
} catch (IOException e) {
};
}
public static void main(String[] args){
notepad_Data obj = new notepad_Data();
obj.escribir("writing in the notepad");
}
}
i tried with this code in the escribir method but doesnt work
for(int i=0; i<1000; ++i){
try {
FileWriter w = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(w);
PrintWriter wr = new PrintWriter(bw);
wr.append(nombreArchivo+" ");
bw.close();
} catch (IOException e) {
};
}
Every time you execute the program, you create a new sava_data file that replaces the previous file with the same name, so your new content is not added.
public class Notepad_Data {
public void escribir(String nombreArchivo) {
FileWriter fw = null;
try{
File f = new File("save_data");
fw = new FileWriter(f, true);
}catch(Exception e){
e.printStackTrace();
}
PrintWriter pw = new PrintWriter(fw);
pw.println(nombreArchivo);
pw.flush();
try{
fw.flush();
pw.close();
fw.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
Notepad_Data obj = new Notepad_Data();
obj.escribir("writing in the notepad11");
}
}
You should place your wr.append inside the loop using the arrayList.size as your condition, what you did here is you placed the whole block inside a for loop, which is not a good idea, one reason is you keep on creating an object of those 3 classes: FileWriter, BufferedWriter and PrintWriter, which is a potential java.lang.OutOfMemoryError: Java heap space error.
I'm writing a code where in data in a file has to be replaced with another file content.
I know how to use a string Replace() function. but the problem here is, I want to replace a string with a entirely new Data.
I'm able to append(in private static void writeDataofFootnotes(File temp, File fout)) the content, but unable to know how do I replace it.
Below is my code.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
public class BottomContent {
public static void main(String[] args) throws Exception {
String input = "C:/Users/u0138039/Desktop/Proview/TEST/Test/src.html";
String fileName = input.substring(input.lastIndexOf("/") + 1);
URL url = new URL("file:///" + input);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
File fout = new File("C:/Users/u0138039/Desktop/TEST/Test/OP/" + fileName);
File temp = new File("C:/Users/u0138039/Desktop/TEST/Test/OP/temp.txt");
if (!fout.exists()) {
fout.createNewFile();
}
if (!temp.exists()) {
temp.createNewFile();
}
FileOutputStream fos = new FileOutputStream(fout);
FileOutputStream tempOs = new FileOutputStream(temp);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
BufferedWriter tempWriter = new BufferedWriter(new OutputStreamWriter(tempOs));
String inputLine;
String footContent = null;
int i = 0;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("class=\"para\" id=\"")) {
footContent = inputLine.replaceAll(
"<p class=\"para\" id=\"(.*)_(.*)\" style=\"text-indent: (.*)%;\">(.*)(.)(.*)</p>",
"<div class=\"tr_footnote\">\n<div class=\"footnote\">\n<sup><a name=\"ftn.$2\" href=\"#f$2\" class=\"tr_ftn\">$4</a></sup>\n"
+ "<div class=\"para\">" + "$6" + "\n</div>\n</div>\n</div>");
inputLine = inputLine.replaceAll(
"<p class=\"para\" id=\"(.*)_(.*)\" style=\"text-indent: (.*)%;\">(.*)(.)(.*)</p>",
"");
tempWriter.write(footContent);
tempWriter.newLine();
}
inputLine = inputLine.replace("</body>", "<hr/></body>");
bw.write(inputLine);
bw.newLine();
}
tempWriter.close();
bw.close();
in.close();
writeDataofFootnotes(temp, fout);
}
private static void writeDataofFootnotes(File temp, File fout) throws IOException {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(temp);
fw = new FileWriter(fout, true);
int c = fr.read();
while (c != -1) {
fw.write(c);
c = fr.read();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
// ...
}
}
}
Here I'm searching for a particular string and saving it in a separate txt file. And once I'm done with the job. I want to replace the <hr /> tag with the entire txt file data.
How can I achieve this?
I'd modify your processing loop as follows:
while ((inputLine = in.readLine()) != null) {
// Stop translation when we reach end of document.
if (inputLine.contains("</body>") {
break;
}
if (inputLine.contains("class=\"para\" id=\"")) {
// No changes in this block
}
bw.write(inputLine);
bw.newLine();
}
// Close temporary file
tempWriter.close();
// Open temporary file, and copy verbatim to output
BufferedReader temp_in = Files.newBufferedReader(temp.toPath());
String footnotes;
while ((footnotes = temp_in.readLine()) != null) {
bw.write(footnotes);
bw.newLine();
}
temp_in.close();
// Finish document
bw.write(inputLine);
bw.newLine();
while ((inputLine = in.readLine()) != null) {
bw.write(inputLine);
bw.newLine();
}
// ... and close all open files
I have tried many times to read a user input and then write it to a file but I haven't find a solution. Here is my code...
The main class.
import java.util.HashMap;
import java.util.Scanner;
public class cShell{
static String Currentpath="C:\\";
public String Current = Currentpath;
static HashMap<String, ICommand> myhashData=new HashMap<String, ICommand>();
public static void main(String[] args)
{
myhashData.put("ltf", new cITF());
myhashData.put("nbc", new cNBC());
myhashData.put("gdb", new cGDB());
myhashData.put("Tedit", new cTedit());
String Input = "";
do{
System.out.print(Currentpath+"> ");
//String Input = "";
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
Input = scan.nextLine().trim();
}
if(Input.equals("exit")){
System.exit(0);
}
if(myhashData.containsKey(Input)){
ICommand myCommand=myhashData.get(Input);
myCommand.Execute();
}
else{
System.out.println("Invalid Command");
}
}while(!Input.equals("exit"));
}
}
This is the class that do the read and write.
import java.util.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
//import java.lang.System.*;
public class cTedit implements ICommand{
#Override
public void Execute() {
String filename = "";
System.out.println("Enter the file name to be edited");
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
filename = scan.nextLine();
}
String line = null;
try{
InputStreamReader ISR = new InputStreamReader(System.in);
//FileReader fileReader = new FileReader(ISR);
FileWriter fileWriter = new FileWriter(cShell.Currentpath+"\\"+filename);
BufferedReader bufferedReader = new BufferedReader(ISR);
System.out.println("Enter text into the file");
while((line = bufferedReader.readLine()) != null){
fileWriter.write(line);
}
bufferedReader.close();
}catch(FileNotFoundException ex){
System.out.println("Unable to open file '" + filename + "'");
}
catch(IOException ex){
System.out.println("Error reading file '" + filename + "'");
}
}
}
My problem is when I enter some text as user input, pressing enter doesn't stop me from entering inputs, but when I press Ctrl+z it ran into an infinite loop.
Try this one in cTedit class.
bufferedReader.readLine() will never return null in your case.
Type exit to come out of loop.
while((line = bufferedReader.readLine()) != null){
if(line.equals("exit")){
break;
}
fileWriter.write(line);
}
Use fileWriter.close() in the end.
Maybe that's not the source of your problem, but I don't think that you need to check the hasnext() condition to read a line :
if(scan.hasNext()){
filename = scan.nextLine();
}
just filename = scan.nextLine(); should be enough.
Use the following
if(Input.equals("exit") || Input.equals("")){
System.exit(0);
}
instead of
if(Input.equals("exit")){
System.exit(0);
}
In order to close the fileWriter after just before exiting add a method closeFile as below.
import java.util.;
import java.io.;
import java.nio.file.Files;
import java.nio.file.Path;
//import java.lang.System.*;
public class cTedit implements ICommand{
private FileWriter fileWriter;
#Override
public void Execute() {
// TODO Auto-generated method stub
String filename = "";
System.out.println("Enter the file name to be edited");
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
filename = scan.nextLine();
}
String line = null;
try{
InputStreamReader ISR = new InputStreamReader(System.in);
//FileReader fileReader = new FileReader(ISR);
fileWriter = new FileWriter(cShell.Currentpath+"\\"+filename);
BufferedReader bufferedReader = new BufferedReader(ISR);
System.out.println("Enter text into the file");
while((line = bufferedReader.readLine()) != null){
fileWriter.write(line);
}
bufferedReader.close();
}catch(FileNotFoundException ex){
System.out.println("Unable to open file '" + filename + "'");
}
catch(IOException ex){
System.out.println("Error reading file '" + filename + "'");
} finally {
fileWriter.close();
}
}
public void closeFile() {
fileWriter.close();
}
}
and then callCloseFile in cShell class just before exiting
I have a list of files in the directory C:\Users\Mahady\Desktop\Java 31122011\src\register\
they are like this....
100100545.txt
100545454.txt etc etc
in each file, file data are like this line by line:
Bob
1234
4834
London
9852
1
My question is, how do i read each files one by one in the directory and for each files read all lines except line 3. i would then like to merge this data in word and create letters. thanks
Detailed Answer....
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileRead {
public static void main(String[] args) {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
File folder = new File("C:/Users/Mahady/Desktop/Java 31122011/src/register/");
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line = null;
int lineCount = 0;
while (null != (line = bufferedReader.readLine())) {
lineCount++;
if (3 != lineCount) {
System.out.println(line);
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Hope this would help you.
Try this:
File dir = new File("C:\\Users\\Mahady\\Desktop\\Java 31122011\\src\\register\\");
for (string fn : dir.list()) {
FileInputStream fstream = new FileInputStream(fn);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println (strLine);
}
in.close();
}
Obviously, you will need to add exception handling code around this skeletal implementation.