I have used the functions oldFile.delete() and newfile.rename("oldFile.txt") both are file object but this is not working, delete function and rename function gives an error,
the source code is below:
package urlFiltering;
import java.io.*;
import java.net.InetAddress;
public class mainForm{
public static void main(String args[]) throws IOException {
String hostName="www.stackoverflow.com";
InetAddress inetAddress=InetAddress.getByName(hostName);
String host=inetAddress.toString();
FileReader inputFile = new FileReader("StoredIp.txt");
File tempFile= new File("tempFile.txt");
BufferedReader bufferReader = new BufferedReader(inputFile);
String line;
while ((line = bufferReader.readLine()) != null) {
if(host.equals(line))
continue;
else
{
if (!tempFile.exists()) {
tempFile.createNewFile();
}
FileWriter fw = new FileWriter(tempFile,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(line);
bw.newLine();
bw.close();
}
}
bufferReader.close();
inputFile.delete();//error
tempFile.renameTo("StoredIp.txt"); //error
}
}
Your inputFile is a FileReader, which doesn't have a delete() method. You can create a File object to represent that file, and give that File as input to the FileReader constructor. Then you can also invoke the delete() method on the File object at the end, instead of on the FileReader. The renameTo() gives you an error because the method expects a File and not a String. Do renameTo(new File("StoredIp.txt")) for it instead. In other words, this:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
public class mainForm {
public static void main(String args[]) throws IOException {
String hostName = "www.stackoverflow.com";
InetAddress inetAddress = InetAddress.getByName(hostName);
String host = inetAddress.toString();
File inputF = new File("StoredIp.txt");
FileReader inputFile = new FileReader(inputF);
File tempFile = new File("tempFile.txt");
BufferedReader bufferReader = new BufferedReader(inputFile);
String line;
while ((line = bufferReader.readLine()) != null) {
if (host.equals(line))
continue;
else {
if (!tempFile.exists()) {
tempFile.createNewFile();
}
FileWriter fw = new FileWriter(tempFile, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(line);
bw.newLine();
bw.close();
}
}
bufferReader.close();
inputF.delete();// no more error
tempFile.renameTo(new File("StoredIp.txt")); // no more error
}
}
Related
I am out of ideas, I've been trying for the whole day to separate one file which has a format of :
AN Aixas
AN Aixirivall
AN Aixovall
AN Andorra la Vella
BR Salto do Mandira
BR Salto do Norte
BR Salto Dollman
BR Salto Grande
BR Salto Pilao
...
and so one, into different files by the name of the Country "AA.txt" and to include all the cities in these separate files. But my program only writes to a certain bunch of files and I cannot figure out why.
I've tried all the writing files classes - same result.
Here is the result, all worked but on a certain bunch of files only.
Here is the code :
package com.fileorganizer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class File2 implements Cloneable {
static InputStream fis = null;
static BufferedReader br = null;
static String state = "";
static String tmp = "";
static File file = null;
static FileWriter fw = null;
static BufferedWriter bw = null;
public static void main(String[] args) {
int a = 0;
try {
fis = new FileInputStream(
new File(
"/Users/Mihail/Documents/WorkSpace/Parse-Starter-Project-1.8.2/ParseStarterProject/res/raw/cities.txt"));
br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
state = line.substring(0, 2);
if (state.substring(0, 1).matches("^[A-Z]+$")
&& state.substring(1, 2).matches("^[A-Z]+$")
&& !tmp.equals(state)) {
file = new File(
"/Users/Mihail/Documents/WorkSpace/Parse-Starter-Project-1.8.2/ParseStarterProject/res/raw/countriesFolder/"
+ state + ".txt");
fw = new FileWriter(file.getAbsoluteFile());
bw = new BufferedWriter(fw);
tmp = state;
}
bw.write(line.substring(3) + "\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (Exception ex) {
}
}
}
}
I am really sorry for such a dumb question. Please help
You don't close bw anywhere, so the contents in the BufferedWriter's buffer are lost.
In my below code I wanted to replace the text "DEMO" with "Demographics" but instead of replacing the text it deletes the entire content of the text file.
Contents inside the file:
DEMO
data
morning
PS: I'm a beginner in java
package com.replace.main;
import java.io.*;
public class FileEdit {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
String readLine, replacedData;
try {
bw = new BufferedWriter(
new FileWriter(
"Demg.ctl"));
br = new BufferedReader(
new FileReader(
"Demg.ctl"));
System.out.println(br.readLine()); //I Get Null Printed Here
while ((readLine = br.readLine())!= null) {
System.out.println("Inside While Loop");
System.out.println(readLine);
if (readLine.equals("DEMO")) {
System.out.println("Inside if loop");
replacedData = readLine.replaceAll("DEMO","Demographics");
}
}
System.out.println("After While");
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You open a Writer to your file, but you don't write anything. This means that your file is replaced with an empty file.
Besides this you also need to close your writer, not just the reader.
And last but not least, your if condition is wrong.
if (readLine.equals("DEMO")) {
should read
if (readLine.contains("DEMO")) {
Otherwise it would only return true if your line contained "DEMO" but nothing else.
I'm updating the answer to my own question.
package com.replace.main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileEdit
{
public static void main(String args[])
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("Demg.ctl"));
String readLine = "";
String oldtext = "";
while((readLine = reader.readLine()) != null)
{
oldtext += readLine + "\r\n";
}
reader.close();
// To replace the text
String newtext = oldtext.replaceAll("DEMO", "Demographics");
FileWriter writer = new FileWriter("Demg.ctl");
writer.write(newtext);
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class part2
{
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException
{
File f1 = new File("one.txt");
File f2 = new File("two.txt");
BufferedReader fr1 = null;
BufferedReader fr2 = null;
//BufferedReader fr3 = null;
BufferedWriter fw = null;
fr1 = new BufferedReader(new FileReader("one.txt"));
fr2 = new BufferedReader(new FileReader("two.txt"));
fw = new BufferedWriter(new FileWriter("res.txt"));
String line1 = fr1.readLine();
String line2 = fr2.readLine();
// merging two files into one
while (line1 != null)
{
fw.write(line1);
fw.newLine();
line1 = fr1.readLine();
}
while (line2 != null)
{
fw.write(line2);
fw.newLine();
line2= fr2.readLine();
}
fw.close();
// sorting a new file
BufferedReader fr3 = null;
BufferedWriter fw1 = null;
fw1 = new BufferedWriter(new FileWriter("res1.txt"));
fr3 = new BufferedReader(new FileReader("res.txt"));
String line3 = fr3.readLine();
ArrayList<String> lineList = new ArrayList<String>();
while (line3 != null)
{
lineList.add(line3);
line3 = fr3.readLine();
}
Collections.sort(lineList);
for(int i=0; i<lineList.size(); i++)
{
fw1.write(lineList.get(i) + "\n");
//line3 = fr3.readLine();
}
}
}
I'm trying to merge two files together into "res.txt", and then sort the merged file alphabetically (and put the sorted lines in "res1.txt"). Everything works until the sorting, to be exact from the while (line3 != null) line, i.e. it reads and merges two files, but doesn't sort them. Any ideas?
Close fw1 prior to exiting the program or it gets removed from memory before the content of the buffer is flushed.
I asked a similar question before regarding I/O using Java.
I'm trying to copy a list of strings into another file.
package file;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class File {
public static void main(String[] args) {
FileWrite fW = new FileWrite();
try (BufferedReader br = new BufferedReader(new FileReader("B:\\inLarge.dat")))
{
String stCurrent;
while ((stCurrent = br.readLine()) != null) {
System.out.println(stCurrent);
fW.serializeAddress(stCurrent, stCurrent);
}
} catch (IOException e) {
e.printStackTrace();
}
//fW.serializeAddress("Boston", "Canada");
}
}
And
package file;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.File;
import java.io.IOException;
public class FileWrite {
public void serializeAddress(String city, String country){
try
{
File file = new File("B:\\outLarge.txt");
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(city + " " + country);
bw.close();
System.out.println("Done");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
But the ending output file has only one result, how do I make it copy everything?
I am thinking buffered-writer somehow needs to be in the loop to write new ones on top of existing ones? But not sure how to implement that.
Thanks a lot.
You are overwriting the file contents every time you call your serialize method, because you didn't open the file in append mode. To prevent overwriting, open the file in append mode:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
However, this is one case where the solution is probably over-engineered. For efficiency you really should be opening your file just once. Here's an example:
public static void main(final String[] args) {
try {
final BufferedReader reader = new BufferedReader(new FileReader("infile.txt"));
final PrintWriter writer = new PrintWriter(new File("outfile.txt"));
String inputLine;
while((inputLine = reader.readLine()) != null) {
writer.println(inputLine);
}
reader.close();
writer.close();
} catch(final Exception e) {
e.printStackTrace();
}
}
You're overwriting the existing file every time you open it. Instead append to it.
Change
FileWriter fw = new FileWriter(file.getAbsoluteFile());
to
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
When trying to create two methods for counting the no. of rows and reading the values of a file, only one of these methods got executed and another is not executed showing the following error :Exception in thread "main" java.lang.RuntimeException: java.io.IOException: Read error
Please look at the following code:
package com.ibm.csvreader;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.io.*;
public class CsvFileReader2 {
public static class opencsvfile {
HashMap <String , String> map= new HashMap <String, String> ();
//csv file containing data
// FileReader strFile = new FileReader("C:/Users/vmuser/Desktop/SampleUpload.csv");
//create BufferedReader to read csv file
// BufferedReader br = new BufferedReader((strFile));
String strLine = "";
int lineNumber ;
public void countrows(FileInputStream fstream) throws Exception{
DataInputStream strFile = new DataInputStream(fstream);
BufferedReader br = new BufferedReader( new InputStreamReader (strFile));
lineNumber =0;
while( (strLine = br.readLine()) != null) {
lineNumber++;
}
System.out.println("no.of rows are :" +lineNumber);
br.close();
}
public void readfile(FileInputStream fstream) throws Exception{
DataInputStream strFile = new DataInputStream(fstream);
BufferedReader br = new BufferedReader( new InputStreamReader (strFile));
lineNumber =0;
while( (strLine = br.readLine()) != null) {
lineNumber++;
String[] tokens = strLine.split(",");
String key = tokens[0].trim();
String nodes = tokens[1].trim();
map.put(key, nodes);
}
System.out.println("map is" + map );
br.close();
System.out.println("File is Closed");
}
}
public static void main(String[] args) throws IOException {
File fl = new File ("C:/Users/vmuser/Desktop/SampleUpload.csv");
FileInputStream fstream = new FileInputStream(fl);
opencsvfile f=new opencsvfile();
try {
f.countrows(fstream);
f.readfile(fstream);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Just a small modification will do the work:
package com.ibm.csvreader;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.io.*;
public class CsvFileReader2 {
public static class opencsvfile {
HashMap <String , String> map= new HashMap <String, String> ();
//csv file containing data
// FileReader strFile = new FileReader("C:/Users/vmuser/Desktop/SampleUpload.csv");
//create BufferedReader to read csv file
// BufferedReader br = new BufferedReader((strFile));
String strLine = "";
int lineNumber ;
public void countrows(FileInputStream fstream) throws Exception{
DataInputStream strFile = new DataInputStream(fstream);
BufferedReader br = new BufferedReader( new InputStreamReader (strFile));
lineNumber =0;
while( (strLine = br.readLine()) != null) {
lineNumber++;
}
System.out.println("no.of rows are :" +lineNumber);
br.close();
}
public void readfile(FileInputStream fstream) throws Exception{
DataInputStream strFile = new DataInputStream(fstream);
BufferedReader br = new BufferedReader( new InputStreamReader (strFile));
lineNumber =0;
while( (strLine = br.readLine()) != null) {
lineNumber++;
String[] tokens = strLine.split(",");
String key = tokens[0].trim();
String nodes = tokens[1].trim();
map.put(key, nodes);
}
System.out.println("map is" + map );
br.close();
System.out.println("File is Closed");
}
}
public static void main(String[] args) throws IOException {
File fl = new File ("C:/Users/vmuser/Desktop/SampleUpload.csv");
FileInputStream fstream = new FileInputStream(fl);
opencsvfile f=new opencsvfile();
try {
f.countrows(fstream);
fstream = new FileInputStream(fl);//include this line
f.readfile(fstream);
} catch (Exception e) {
throw new RuntimeException(e);
}
finally{
if(fstream!=null)
fstream.close();//be sure to close all streams at last
}
}
}
Close all other streams as well. Above code will work for you.Cheers.
When you close your BufferedReader, it also closes the nested classes, including the FileInputStream.
Instead of closing it, you should try and reset() it to restart reading it from the start.
Or you must re-open the FileInputStream.