Find and replace words in a text file (Java GUI) - java

I'm looking to create a find and replace java application which prompts users to call to a text file, print it out to a new file, ask user for a search word or phrase and a word to replace that searched word with. Here is the code I have so far. I can read the contents from the first file just fine but cannot write the contents from the first file to another. This is all done within a GUI code below
String loc = jTextField1.getText(); //gets location of initial file or "source"
String file = jTextField4.getText(); //new file path
String find = jTextField2.getText(); //find word inputted by user
String word = jTextField3.getText(); //replace "find" with word inputted by user
String line = null;
try {
BufferedReader br = new BufferedReader(new FileReader(loc));
while ((line = br.readLine()) !=null)
} catch (FileNotFoundException ex) {
Logger.getLogger(Assign6GUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Assign6GUI.class.getName()).log(Level.SEVERE, null, ex);
}

To write content to a file you need to use BufferedWriter
public static void writetoFile(String str, String FILE_PATH, String FILENAME ) {
BufferedWriter writer = null;
try {
File file = new File(FILE_PATH);
// if file doesnt exists, then create it
if (!file.exists()) {
file.mkdir();
}
file = new File(FILE_PATH + FILENAME);
file.createNewFile();
writer = new BufferedWriter(new FileWriter(file));
writer.write(str);
} catch (IOException e) {
LOGGER.debug(e);
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (Exception e) {
LOGGER.debug(e);
}
}
}
to replace words in a string you should use the replace function in java
String str = someString.replace("OldText", "NewText");

Related

Why can't I neither delete nor rename the file?

While creating a method to my class, I got an unexpected problem. I've tried solutions from other theards, but they just don't work for me. My method should simply find the line specified, copy the file skipping unnecessary line, delete the original file and rename temporary file to the name of original file. It succesfuly creates new file as expected, but then fails to delete previous one as it fails to rename temporary file to original. I can't figure out, why?
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
File filePath = new File(path);
BufferedReader reader = new BufferedReader(new FileReader(file_name + ".txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
filePath.delete();
temp.renameTo(theFile);
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
Try this code:
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
BufferedReader reader = new BufferedReader(new FileReader(theFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
theFile.delete();
temp.renameTo(file_name + ".txt");
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
I could suggest a couple of reasons why the delete and/or rename might fail, but there is a better way to solve your problem than guessing1.
If you use Path and the Files.delete(Path) and Files.move(Path, Path, CopyOption...) methods, they will throw exceptions if the operations fail. The exception name and message should give you clues as to what is actually going wrong.
The javadoc is here and here.
1 - Here are a couple of guesses: 1) the file has been opened elsewhere, and it is locked as a result. 2) You don't have access to delete the file.

formatting while writing a document

I am reading a txt file into a String buffer and writing the content into a word document using OutputStreamWriter.
The problem is that the formatting is not retained in the document. The spaces and the line breaks are not retained as in the text file. The txt file is formatted properly with spaces, page breaks, and tabs. I want to replicate the txt in word document. Please suggest how can the same formatting be retained. The link to the file is: http://s000.tinyupload.com/index.php?file_id=09876662859146558533.
This is the sample code:
private static String readTextFile() {
BufferedReader br = null;
String content = null;
try {
br = new BufferedReader(new FileReader("ORDER_INVOICE.TXT"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
sb.append(System.lineSeparator());
}
content = sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
private static void createDocument(String docName, String content) {
FileOutputStream fout = null;
try {
fout = new FileOutputStream(docName);
OutputStreamWriter out = new OutputStreamWriter(fout);
out.write(content);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Try to change your readTextFile() like this and try.
BufferedReader br = null;
String content = null;
try {
br = new BufferedReader(new FileReader("ORDER_INVOICE.TXT"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while(line != null) {
content += line + "\n";
line = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
Actually if your using java 7, you can use try-with-resources in order to decrease the number of lines in your code.
Try to avoid printing \n chars. Use \r\n for Windows - remember that line separators differ across platforms.
A more reliable way is to use PrintWriter, see
How to write new line in Java FileOutputStream
After the discussion in comments:
the source file has unix line breaks
the output file is expected to have Windows line breaks
we shall strip the 0x0c (form feed - i.e. move to next page on the printer) from the source file, as it is non-printable.
public static void main(String[] args) throws IOException {
String content = new String(Files.readAllBytes(Paths.get("f:\\order_invoice.txt")))
.replace("\u000c","");
PrintWriter printWriter=new PrintWriter(new FileWriter("f:\\new_order_invoice.txt"));
for (String line:content.split("\\n")) {
printWriter.println(line);
}
printWriter.close();
}
So:
read the file as it is into a String
get rid of the form feed (0x0c, unicode u000c)
split the string at unix line breaks \n
write it out line by line using PrintWriter which uses the platform default line ending, i.e. windows cr-lf.
Remember that you can actually do this in one line, using a regexp to replace unix line endings to windows line endings in the string representing the whole file, and use Files.write to write out the whole file in one line. However this presented solution is probably a bit better as it always uses platform native line separators.

Editing a file using FileWriter

I am trying to Edit a existing file which is in my R.raw folder
i am able to read the file
but when i run the write function it is not working .
public void tofile(View v){
BufferedWriter bw=null;
FileWriter fw =null;
try {
String path = ("/Page2/res/raw/text.txt");
File file = new File(path);
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write("hello");
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
i even tried
fw = new FileWriter(file,true);
if i add toast between even line it seems to get stuck at
fw = new FileWriter(fw);
You can't able to Write
As #CommonsWare said you can't write on resources but you could use internal storage using openFileOutput and openFileInput and BufferedReaders and BufferedWriters. You can check it here
from the answer of #rodkarom in the following link
Write to a Text File Resource in Android
and #Andro Selva says same thing in the following link
How to write a file in Android to the raw folder?
you can able to read the content from the textfile which is present in the res/raw folder dude
read the file from res folder
public String readStringFromResource(Context ctx, int resourceID) {
StringBuilder contents = new StringBuilder();
String sep = System.getProperty("line.separator");
try {
InputStream is = ctx.getResources().openRawResource(R.raw.trails);
BufferedReader input = new BufferedReader(new InputStreamReader(is), 1024*8);
try {
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(sep);
}
}
finally {
input.close();
}
}
catch (FileNotFoundException ex) {
Log.e(TAG, "Couldn't find the file " + resourceID + " " + ex);
return null;
}
catch (IOException ex){
Log.e(TAG, "Error reading file " + resourceID + " " + ex);
return null;
}
return contents.toString();
}
check it and inform

BufferedReader not reading complete .txt file

I'm trying to read a moderately sized txt file (65,00 words) into a String, then a string array. The bufferedreader throws the "could not read file" catch. When I clear it, a small part of the contents of the text file is shown in the system.out. I do not get the error with smaller text files. I'm a beginner and I'm having a lot of trouble trying to narrow down the issue.
Why isn't the BufferedReader ingesting the entire file? And why is the "could not read file" error being thrown?
public class Main {
public static void main(String[] args) {
final Guid Main = new Guid(); //creates instance of Guid
Main.mergeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
merge();
}
});
}
static void merge()
{
//read file and turn into string
String pathone = open(Guid.PathOne);
System.out.print(pathone);
//parse and format
//String[] oneArray = pathone.replace("\n"," ").split(" ");
//get pathtwo text
//String pathtwo = open(Guid.PathTwo);
//parse and format
//load into array
//compare array entries
//add new array entry
//sort array
//write array to paththree file
//for(int i=0; i<oneArray.length;i++)
//{
//System.out.println(oneArray[i]);
//}
}
public static String open(JTextArea Path)
{
String record = null;
FileReader frFile = null;
try {
frFile = new FileReader(Path.getText());//gets file from Path
BufferedReader brFile = new BufferedReader(frFile);//creates buffered reader
record = brFile.readLine() + "\n"; //gets contents of file and puts it into a string
brFile.mark(0);
while (brFile.read() != -1) //loop to read the rest of the text file
{
brFile.reset();
record = record + brFile.readLine() + "\n";
brFile.mark(0);
}
}
catch (FileNotFoundException e) //catch path is in error
{
JFrame frame = null;
JOptionPane.showMessageDialog(frame, "Could not find file.");
}
catch (IOException e) //catch if file cannot be read
{
JFrame frame = null;
JOptionPane.showMessageDialog(frame, "Could not read file.");
}
try { //closes file
frFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return record;
}
}
Do in this way. Remove reset() and mark() methods if you want to read the entire file.
StringBuilder record = new StringBuilder();
BufferedReader brFile = new BufferedReader(frFile);
String line = null;
while ((line = brFile.readLine()) != null) {
record.append(line).append("\n");
}
Note:
Don't forget to close the stream.
Use finally block to close the stream
Use StringBuilder or StringBuffer to append the string.
Use System.getProperty("line.separator") to get the system specific line separator
Have a look at Java7 try-with-resources Statement advantage
readLine will read the first line of your document.
Try with it (not tested):
String lineReaded;
while ((lineReaded=brFile.readLine())!=null)
{
record +=linereaded+"\n";
}
Niko
You might like to use Files.readAllLines

Reading multiple text file in Java

I have few text files. Each text file contains some path and/or the reference of some other file.
File1
#file#>D:/FilePath/File2.txt
Mod1>/home/admin1/mod1
Mod2>/home/admin1/mod2
File2
Mod3>/home/admin1/mod3
Mod4>/home/admin1/mod4
All I want is, copy all the paths Mod1, Mod2, Mod3, Mod4 in another text file by supplying only File1.txt as input to my java program.
What I have done till now?
public void readTextFile(String fileName){
try {
br = new BufferedReader(new FileReader(new File(fileName)));
String line = br.readLine();
while(line!=null){
if(line.startsWith("#file#>")){
String string[] = line.split(">");
readTextFile(string[1]);
}
else if(line.contains(">")){
String string[] = line.split(">");
svnLinks.put(string[0], string[1]);
}
line=br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Currently my code reads the contents of File2.txt only, control does not come back to File1.txt.
Please ask if more inputs are required.
First of all you are jumping to another file without closing the current reader and when you come back you lose the cursor. Read one file first and then write all its contents that match to another file. Close the current reader (Don't close the writer) and then open the next file to read and so on.
Seems pretty simple. You need to write your file once your svnLinks Map is populated, assuming your present code works (haven't seen anything too weird in it).
So, once the Map is populated, you could use something along the lines of:
File newFile = new File("myPath/myNewFile.txt");
// TODO check file can be written
// TODO check file exists or create
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
fos = new FileOutputStream(newFile);
osw = new OutputStreamWriter(fos);
bw = new BufferedWriter(osw);
for (String key: svnLinks.keySet()) {
bw.write(key.concat(" my separator ").concat(svnLinks.get(key)).concat("myNewLine"));
}
}
catch (Throwable t) {
// TODO handle more gracefully
t.printStackTrace();
if (bw != null) {
try {
bw.close();
}
catch (Throwable t) {
t.printStackTrace();
}
}
Here is an non-recursive implementation of your method :
public static void readTextFile(String fileName) throws IOException {
LinkedList<String> list = new LinkedList<String>();
list.add(fileName);
while (!list.isEmpty()) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File(list.pop())));
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("#file#>")) {
String string[] = line.split(">");
list.add(string[1]);
} else if (line.contains(">")) {
String string[] = line.split(">");
svnLinks.put(string[0], string[1]);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
}
}
}
Just used a LinkedList to maintain the order. I suggest you to add some counter if you to limit the reading of files to a certain number(depth). eg:
while (!list.isEmpty() && readCount < 10 )
This will eliminate the chance of running the code to infinity(in case of circular reference).

Categories