This is a method to encrypt/decrypt a file(SourceFile.txt) and save the result in another file(ConvertedFile.txt)
private void crypto(int index, int k) throws IOException// 0 -> encrypt 1 -> decrypt
{
FileReader in;
FileWriter out;
try
{
in = new FileReader("SourceFile.txt");
out = new FileWriter("ConvertedFile.txt");
}
catch(FileNotFoundException e)
{
System.out.println("File NOT Found.");
return;
}
c = new cipher(k);
Scanner sc = new Scanner(in);
String line,token;
StringTokenizer st;
while(sc.hasNextLine())
{
line = sc.nextLine();
st = new StringTokenizer(line," ");
while(st.hasMoreTokens())
out.write(c.convert(st.nextToken(),index)+" ");
out.write(10);
}
in.close();
out.close();
}
If the sourceFile has something in it like
Mary had
a little
lamb
The convertedFile contains the encryption as
Qevc leh
e pmxxpi
peqf
Is there anyway how I can use the FileWriter to print a '\n'(new line) at the end of every line?
I even tried the out.write(10)... didn't work
Use PrintWriter
PrintWriter p = new PrintWriter(out);
p.println(str);
You can wrap the FileWriter in a BufferedWriter and use newLine()
BufferedWriter bw = new BufferedWriter(new FileWriter("text.txt"));
bw.write(line);
bw.newLine();
You missed braces of while loop.
while(sc.hasNextLine())
{
line = sc.nextLine();
st = new StringTokenizer(line, " ");
while(st.hasMoreTokens())
{ // Add braces here for newline
out.write(c.convert(st.nextToken(), index) + " ");
out.write(10); //Without braces it will be skipped.
}
}
FileWriter out = null;
try {
out = new FileWriter("F:/work1.txt");
out.write("Rakesh");
out.write("\r\n");
out.write("KR");
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Then the file contains:
Rakesh
KR
Or You Can Use BufferedWriter as
public void fileWrite(String fileName,ArrayList<String> str){
File f ;
FileWriter fw = null;
BufferedWriter bw = null;
try {
f = new File(fileName);
fw = new FileWriter(f.getAbsoluteFile());
bw = new BufferedWriter(fw);
for(String i:str){
bw.write(i);
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(bw!=null)
bw.close();
if(fw!=null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
How can I open a .txt file and read numbers separated by enters or spaces into an array list?
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
Good news in Java 8 we can do it in one line:
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
in.close();
}
This will read line by line,
If your no. are saperated by newline char. then in place of
System.out.println (strLine);
You can have
try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}
If it is separated by spaces then
try{
String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
}catch(NumberFormatException npe){
//do something
}
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT::
Success
26
Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file.
input-convert-Write-Process... its that simple.
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;
}
Hey friends try to replace some commas in my database, can someoone give me advide what wrong is with my code, have already the replace eveything is done, but nothing happends
try {
BufferedReader br = new BufferedReader(new FileReader("C:/Users/Sei_Erfolgreich/Desktop/convert.txt"));
String zeile; try {
while ((zeile = br.readLine()) != null) {
zeile = zeile.replaceAll("\",\"", "\uffff")
.replaceAll(",", "")
.replaceAll("\uffff", "\",\"");
System.out.println(zeile);
}
File newTextFile = new File("C:/Users/Sei_Erfolgreich/Desktop/convert2.txt");
FileWriter fw = new FileWriter(newTextFile);
fw.write(zeile);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
you are writing string after coming out from loop so that string whould be null, try out this code
try {
BufferedReader br = new BufferedReader(
new FileReader("C:/Users/Sei_Erfolgreich/Desktop/convert.txt"));
String zeile;
try {
File newTextFile = new File("C:/Users/Sei_Erfolgreich/Desktop/convert2.txt");
FileWriter fw = new FileWriter(newTextFile);
while ((zeile = br.readLine()) != null) {
zeile = zeile.replaceAll("\",\"", "\uffff").replaceAll(",",
"").replaceAll("\uffff", "\",\"");
System.out.println(zeile);
fw.write(zeile);
}
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
Try this :
BufferedReader br = new BufferedReader(new FileReader("C:/Users/Sei_Erfolgreich/Desktop/convert.txt"));
File newTextFile = new File("C:/Users/Sei_Erfolgreich/Desktop/convert2.txt");
FileWriter fw = new FileWriter(newTextFile);
String zeile;
try {
while ((zeile = br.readLine()) != null) {
zeile = zeile.replaceAll("\",\"", "\uffff").replaceAll(",", "").replaceAll("\uffff", "\",\"");
System.out.println(zeile);
fw.write(zeile);
}
fw.close();
}
Earlier what you were doing, you read the file until last line and saving only one last line instead of whole file text.
You're writing null because you don't write until after your while loop (which terminates when zeile is null). Also, you should be closing everything in a finally block (or using a try-with-resources. Also, I suggest you use a PrintWriter so you can match your System.out.println()(s). Something like,
File newTextFile = new File("C:/Users/Sei_Erfolgreich/Desktop/convert2.txt");
try (BufferedReader br = new BufferedReader(new FileReader(
"C:/Users/Sei_Erfolgreich/Desktop/convert.txt"));
PrintWriter fw = new PrintWriter(newTextFile)) {
String zeile;
while ((zeile = br.readLine()) != null) {
zeile = zeile.replaceAll("\",\"", "\uffff").replaceAll(",", "")
.replaceAll("\uffff", "\",\"");
System.out.println(zeile);
fw.println(zeile);
}
} catch (Exception e) {
e.printStackTrace();
}
I'm having a problem with reading and writing arraylist to a text file. Specifically with reading. What I'm trying to do is read from a text file and transfer it to an array list. After which i would edit the list and write it back to the text file. I think I go the writing done but not the reading. I've tried reading several similar questions here but cant seem to inject it into my code.
Reading code
public void read(List<AddressBook> addToList){
BufferedReader br = null;
try {
String currentLine= "";
br = new BufferedReader(new FileReader("bank_account.csv"));//file na gusto mo basahin
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
for (AddressBook read : addToList) {
br.read(read.getName() + read.getAddress() + read.getTelNum() + read.getEmailAdd());
addToList.add(read);
} }
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Here's what I've done with the write
public void write(List<AddressBook> addToList) {
try {
File file = new File("bank_account.csv"); //file
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//FileWriter fw = new FileWriter(file.getAbsoluteFile());
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
for (AddressBook write : addToList) {
bw.write(write.getName() + "," + write.getAddress() + "," + write.getTelNum() + "," + write.getEmailAdd());
bw.newLine();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
for (AddressBook read : addToList) {
br.read(read.getName() + read.getAddress() + read.getTelNum() + read.getEmailAdd());
addToList.add(read);
}
}
I bet in there you will need to do something like:
reading each line
parsing it (each line is a CSV)
creating a new AddressBook object with all that info
add it to the collection
The code for that will look like:
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
String[] splitted = currentLine.split(",");
AddressBook address = new AddressBook(splitted[0], splitted[1], splitted[2], splitted[3]);
addToList.add(address);
}
Of course there are things you will need to check and validate, but that is roughtly it.
Maybe you need read method like this.
public void read() {
List<AddressBook> addToList =new ArrayList<AddressBook>();
BufferedReader br = null;
try {
String currentLine= "";
br = new BufferedReader(new FileReader("bank_account.csv"));//file na gusto mo basahin
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
// for (AddressBook read : addToList) {
String[] split =currentLine.split(",");
AddressBook read = new AddressBook();
read.setName(split[0]);
read.setAddress(split[1]);
read.setTelNum(split[2]);
read.setEmailAdd(split[3]);
// br.read(read.getName() + read.getAddress() + read.getTelNum() + read.getEmailAdd());
addToList.add(read);
// }
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
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
}
}
}