Can't read data from a text file - java

I have text file with name pwd.txt located in projectfolder->src->pwd.txt
and I am accessing this file as follows:
File f1 = new File("src\\pwd.txt");
if(f1.exists()==false){
System.out.println("file not");
}
FileReader fr = new FileReader(f1);
while ((ch = fr.read()) != -1) {
pass = pass + (char) ch;
}
LoginForm.pwd = pass;
fr.close();
Well, let me tell you first that I am able to access this file when running within the IDE (Eclipse) but I am not able to access that filepwd.txt when I have made the jar file.
When i saw the contents of that jar file, I can see the file pwd.txt

Try following code, i hope it will help you.
BufferedReader br = null;
//first open the file
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream("src\\pwd.txt")));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
return;
}
try {
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (IOException e) {
System.out.println("ERROR:"+e);
}

Related

I have a filewriter method that only ouputs to the file when i close it

String filePath = "Seat";
static void modifyFile(String filePath, String oldString, String newString) {
File fileToBeModified = new File(filePath);
String oldContent = "";
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(fileToBeModified));
//Reading all the lines of input text file into oldContent
String line = reader.readLine();
while (line != null) {
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
//Replacing oldString with newString in the oldContent
String newContent = oldContent.replaceAll(oldString, newString);
//Rewriting the input text file with newContent
writer = new BufferedWriter(new FileWriter(fileToBeModified));
writer.write(newContent);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//Closing the resources
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This method is meant to change a certain line in a file the method itself works when run but it only changes the line when i close the program which is when it closes the writer, i looked it up and add writer.flush() earlier on in the code to see if that would work but i still have the same problem
You are trying to read from and write to the same file.
You cannot do both operations at the same time as the file will get locked. close the reader and then do the write operation.

How to read value in CSV file

Need help from you regarding a Scenario, i.e., I have to take a value from DB like "42258258.2300" and convert this into "42,258,258.00" value.
And again need to check whether this value present in downloaded CSV file.
I used below code for read from CSV file but am not getting the output. Kindly help me on this.
String strFile = "outputfile.csv";
FileInputStream fstream = new FileInputStream(strFile);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String ss = "$42,699,561.00";
if(strLine.contains(ss)){
System.out.println ("Success"); }
}
in.close();
What do you get if you print strLine? Are you really getting the string?
This code works for me
public void getFileInformation(){
String strFile = "/Users/myUser/Documents/outputfile.csv";
BufferedReader br = null;
String strLine = "";
String ss = "$42,699,561.00";
try {
br = new BufferedReader(new FileReader(strFile));
while ((strLine= br.readLine()) != null) {
if(strLine.contains(ss)){
System.out.println ("Success");
}else{
System.out.println (strLine);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
But the content "$42,699,561.00"; should really exist in the file

JAVA removing a line from a .txt file with a keyword

try {
File inFile = new File("books.txt");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile + "temp.txt");
BufferedReader br = new BufferedReader(new FileReader("books.txt"));
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) {
String lineToRemove;
lineToRemove = JOptionPane.showInputDialog("Enter line to remove");
if (!line.trim().contains(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();
}
}
I am trying to create a method that will delete a line of code in my .txt file if I enter a word that is contained in that line. My problem is that when I run this, the test says that it could not delete the file. Is there something wrong with the code? My code is also delimited with # if that may be adding to the problem. A sample output would be :
Giants#James#1993
I've tested your code with minor changes (noted by #Andreas while I was writing this) and it works as expected
public static void main(String[] args) {
try {
File inFile = new File("C:\\rirubio\\books.txt");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File("C:\\rirubio\\books.txt" + "_temp");
BufferedReader br = new BufferedReader(new FileReader(inFile));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
String lineToRemove = JOptionPane.showInputDialog("Enter line to remove");
//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().contains(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();
}
}

How to write in existing file from list using Java by removing duplicate data?

I want to write in file that exists.
My data is in the form of java list.
Here is a sample of data :
snmp,192.168.20.1,cloud,
snmp,192.168.20.2,cloud,
I want to add line snmp,192.168.20.1,cloud123 in the file.
It should update existing file content i.e.(snmp,192.168.20.1,cloud) by new contents given.
And if provided contents different from contents of file then append it to file?
Here is my workaround---
String tempFile = RunMTNew.instdir + "/var/";
File tempFileName = new File(tempFile+"hosts.tempFile");
try{
if(!tempFileName.exists()) {
tempFileName.createNewFile();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
catch ( IOException ioe){
ioe.printStackTrace();
System.out.println("Exception occured while creating temp file");
}
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
PrintWriter tempoutfile= null;
while((line = bufferedReader.readLine()) != null) {
System.out.println("line before if "+ line);
if(line!=null || (line = line.trim()) != "" ){
System.out.println("line at start of while" + line);
String[] lineFromFile = line.split(",");
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)));
ListIterator atwlist = arraytowrite.listIterator();
String lineToWriteInFile = "";
while (atwlist.hasNext()) {
ArrayList atwlistline = (ArrayList) atwlist.next();
System.out.println("array" + atwlistline);
String lineToAdd = atwlistline.toString();
lineToWriteIfNotFound = lineToAdd;
System.out.println("After converting to string line is" + lineToAdd);
System.out.println("lineFromFile contents are "+ lineFromFile[1]);
if(lineToAdd.contains(lineFromFile[1])){
lineToWriteInFile = lineToAdd;
}
else{
lineToWriteInFile = line;
}
}
try{
tempoutfile = new PrintWriter(new BufferedWriter(new FileWriter(tempFileName, true)));
System.out.println("writing in file" +lineToWriteInFile);
tempoutfile.write(lineToWriteInFile);
tempoutfile.write("\n");
}catch(IOException ioe){
ioe.printStackTrace();
System.out.println("Exception occured while writing in tempFile");
}
tempoutfile.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Exception occured in outer try block");
}
}//end of if
}// end of while
try{
FileReader tempfileReader = new FileReader(tempFile+"hosts.tempFile");
BufferedReader tempBufferedReader = new BufferedReader(tempfileReader);
FileWriter fosFinal = new FileWriter(filename);
PrintWriter outFinal = new PrintWriter(fosFinal);
while((line = tempBufferedReader.readLine()) != null) {
System.out.println("line from tempfile to write in main " + line);
outFinal.write(line);
}
}catch(IOException ie){
ie.printStackTrace();
System.out.println("Exception occured while reading from temp and write into main file");
}
Use temp file to store temporarily contents of file.
Here is a code :
ListIterator atwlist = arraytowrite.listIterator();
while (atwlist.hasNext()) {
ArrayList atwlistline = (ArrayList) atwlist.next();
ListIterator atwlistlineL = atwlistline.listIterator();
while (atwlistlineL.hasNext()) {
firstWriter.write((String) atwlistlineL.next());
firstWriter.write(",");
}
//firstWriter.write("\n");
System.out.println(atwlistline);
}
firstWriter.close();
//Write original file contents to another file i.e. tempFile2
try{
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
String line = "";
while((line = bufferedReader.readLine()) != null) {
secondWriter.write(line);
secondWriter.write("\n");
}
secondWriter.close();
bufferedReader.close();
}catch(IOException ie){
ie.printStackTrace();
System.out.println("Exception occured while reading from main file");
}
//check and remove duplicate entries from file
try{
FileReader singleDeviceReader = new FileReader(file1Path);
FileReader duplicateDeviceReader = new FileReader(file2Path);
finalWriter = new PrintWriter(filename);
BufferedReader bufferedReader1 = new BufferedReader(singleDeviceReader);
BufferedReader bufferedReader2 = new BufferedReader(duplicateDeviceReader);
String line1 = null;
String line2 = null;
boolean fileWriteFlag = false;
String ifNotFind = "";
while((line1 = bufferedReader1.readLine())!=null){
String[] line1Split = line1.split(",");
ifNotFind = line1;
while((line2 = bufferedReader2.readLine())!=null){
String[] line2Split = line2.split(",");
if (line2Split[1].equals(line1Split[1])){
finalWriter.write(line1);
finalWriter.write("\n");
fileWriteFlag = true;
}
else {
finalWriter.write(line2);
finalWriter.write("\n");
}
}
}
if(!fileWriteFlag){
finalWriter.write(ifNotFind);
}
finalWriter.close();
bufferedReader1.close();
bufferedReader2.close();
File t1 = new File (file1Path);
File t2 = new File (file1Path);
if (t1.exists()){
t1.delete();
}
if (t2.exists()){
t2.delete();
}
}catch (IOException ioe ){
ioe.printStackTrace();
System.out.println("Exception occured while reading both temp files");
}
Instead of checking and comparing the content from the file I suggest you create list with unique items. Which will save your time to parse the file content and update operations on file and your code as well
First get all the existing data set to a list. now iterate your new list(which need to append) using a for loop and get a inner loop and check condition and add/skip.
Pseudo code:
List my_existing_list;
List my_new_list;
foreach(my_new_list){
foreach(my_existing_list){
if(equal to an existing item){
//skip
}else{
//append to file
}
}
}

Reading/Writing Files in Java and Adding Line Numbers

I have the following assignment to complete:
Wrote a program that reads a file and writes a copy of the file to another file with line numbers inserted.
So far, I wrote the code that is posted below. This code reads and copies the text to another file, but I cannot figure out how to number each line in the new text file. Can someone please advise me on how to do so?
import java.io.*;
class FileCopy
{
public static void main(String[] args)
{
try
{
File fileIn = new File("Assign4.txt");
File fileOut = new File("target.txt");
FileInputStream streamIn = new FileInputStream(fileIn);
FileOutputStream streamOut = new FileOutputStream(fileOut);
int c;
while ((c = streamIn.read()) != -1)
{
streamOut.write(c);
}
streamIn.close();
streamOut.close();
}
catch (FileNotFoundException e)
{
System.err.println("FileCopy: " + e);
}
catch (IOException e)
{
System.err.println("FileCopy: " + e);
}
}
}
Thank you, I appreciate your help.
I will suggest BufferedReader (for sure) and PrintWriter. PrintWriter is a richer API compared to BufferedWriter.
You can you BufferedReader and BufferedReader to read and write text file:
BufferedReader br = new BufferedReader(new FileReader("Assign4.txt"));
BufferedWriter writer = new BufferedWriter( new FileWriter("target.txt"));
try {
int count = 1;
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(count++);
sb.append(line);
sb.append("\n");
writer.write(line);
line = br.readLine();
}
} finally {
br.close();
writer.close();
}

Categories

Resources