Trying to alter a text file in java - java

Here is my code:
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Filter{
Message myMessage;
Scanner input;
Scanner input2;
String sender;
String subject;
String emailMIN;
String line;
String line2;
ArrayList<String> blacklist = new ArrayList<String>();
ArrayList<String> keywords = new ArrayList<String>();
ArrayList<String> subjectWords = new ArrayList<String>();
ArrayList<String> emails = new ArrayList<String>();
//String[] lines;
File SpamMessage;
File inFile;
File inFile2;
File tempFile;
String[] lines;
public Filter(Message m,String blacklistFile, String keywordFile, String Spam)throws IOException{
inFile = new File(blacklistFile);
inFile2 = new File(keywordFile);
input = new Scanner (inFile);
input2 = new Scanner (inFile2);
myMessage =m;
SpamMessage=new File(Spam);
}
public void filter() throws IOException{
PrintWriter output = new PrintWriter(SpamMessage);
while(input.hasNextLine()){
line = input.nextLine();
//System.out.println(line);
if(line!=null)
blacklist.add(line);
}
while(input2.hasNextLine()){
line2 = input2.nextLine();
//System.out.println(line2);
if(line!=null)
keywords.add(line2);
}
emails=myMessage.getEmails();
// System.out.println(emails.size() + emails.get(1));
for(int i = 0; i < emails.size(); i++){
// boolean isSpam = false;
lines = emails.get(i).split("\n");
// System.out.println(lines[5] + lines[7]);
sender = lines[2].substring(lines[2].indexOf('<'), lines[2].indexOf('>'));
//` System.out.println(sender);
emailMIN = lines[6].substring(lines[6].indexOf('<'), lines[6].indexOf('>'));
// System.out.println(emailMIN);
for(int j =0; j<lines.length; j++)
{
if(j==2)
{
for(String blacklist2: blacklist)
{
// System.out.println(blacklist2);
if(lines[j].contains(blacklist2))
{
output.println(emailMIN);
}
// output.close();
}
}
if(j==5 || j>=7)
{
// System.out.println(keywords.size());
for(String keywords2: keywords)
{
// System.out.println(keywords2);
if(lines[j].contains(keywords2))
{
output.println(emailMIN);
}
// output.close();
}
}
//addKeywords();
}
}
output.close();
addKeywords();
}
public void addKeywords() throws IOException
{
tempFile = new File("tempFile.txt");
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
for(int i=0; i<lines.length; i++)
{
if(i==5){
String[] words = lines[i].split(" ");
for(String word: words){
if(word.length()>=6){
subjectWords.add(word +"\n");
//System.out.println(subjectWords);
}
}
keywords.addAll(subjectWords);
pw.println(keywords);
}
}
pw.close();
if (!inFile2.delete()) {
//System.out.println("Could not delete file");
return;
}
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile2)){
//System.out.println("Could not rename file");
}
}
}
I'm trying to update the list of words in the keywords txt file right now it does update it but it puts it in the format [generic, pharmacy, little, inside]
Which is wrong because then if I run my code again it is searching if the file contains [generic, pharmacy, little, inside] and I need it to search for every word not the plus a comma or brace. So basically I want it to copy the words in a list format like this
generic
pharmacy
little
inside
That way it searches for each individual word. I figured out how to do this part. Now, how do I add the senders to a different text file? Also is there a way to modify this so it doesn't add the same keywords twice? Thanks

It is because you are writing an array to the file which causes the toString method of it to be called. Write every single item instead.
Instead of pw.println(keywords); 
Do:
for (String keyword : keywords)
{ 
pw.println(keyword.trim());
}
Or, if every word contains \n already, this should work
for (String keyword : keywords)
{ 
pw.print(keyword);
}

Instead of doing:
pw.println(keywords);
you should instead loop through the array and add each line individually.
for(int i = 0; i < keywords.length; i++) {
pw.println(keywords[i]);
}

That was because you are printing an ArrayList object. In your code, keywords is instance of the List and which would you give you an output of [aa,bb] . More over you would get duplicate words since these list instance are class variables, and printed inside a loop
keywords.addAll(subjectWords);
pw.println(keywords);
Either you can loop around keywords outside the for loop or print the word before adding to list.

Related

Scanning a text file into an array and omitting one specified line

I'm a beginner and need some help. I'm trying to scan a text file into an array line by line, but omitting one line. My text file is
i am
you are
he is
she is
it is
I want to create a method that will scan this and put elements into an array with an exception for one line (that is chosen by entering the String as a parameter for the method). Then erase the original text file and print there the created array (without that one deleted line). Sorry, I suck at explaining.
I have tried this:
public static void deleteLine(String name, String line) throws IOException {
String sc = System.getProperty("user.dir") + new File("").separator;
FileReader fr = new FileReader(sc + name + ".txt");
Scanner scan = new Scanner(fr);
int n = countLines(name); // a well working method returning the number if lines in the file (here 5)
String[] listArray = new String[n-1];
for (int i = 0; i < n-1; i++) {
if (scan.hasNextLine() && !scan.nextLine().equals(line))
listArray[i] = scan.nextLine();
else if (scan.hasNextLine() && scan.nextLine().equals(line))
i--;
else continue;
}
PrintWriter print = new PrintWriter(sc + name + ".txt");
print.write("");
for (int i = 0; i < n-2; i++) {
print.write(listArray[i] + "\n");
}
print.close()
}
I get an error "Line not found" when I enter: deleteLine("all_names","you are") (all_names is the name of the file). I'm sure the problem lies in the for-loop, but I have no idea why this doesn't work. :(
//SOLVED//
This code worked after all. Thanks for answers!
public static void deleteLine(String name, String line) throws IOException{
String sc = System.getProperty("user.dir") + new File("").separator;
FileReader fr = null;
fr = new FileReader(sc+name+".txt");
Scanner scan = new Scanner(fr);
int n = LineCounter(name);
String[] listArray = new String[n-1];
for (int i = 0; i < n-1; i++) {
if (scan.hasNextLine()) {
String nextLine = scan.nextLine();
if (!nextLine.equals(line)) {
listArray[i] = nextLine;
}
else i--;
}
}
PrintWriter print = new PrintWriter(sc+name+".txt");
print.write("");
for(int i=0;i<n-1;i++){
print.write(listArray[i]+System.lineSeparator());
}
print.close();
}
You are reading the lines twice scan.nextLine() while comparing and because of that you run out of the lines.
Replace your loop with this one or similar
for (int i = 0; i < n; i++) {
if (scan.hasNextLine()) {
String nextLine = scan.nextLine();
if (nextLine.equals(line)) {
listArray[i] = nextLine;
}
}
}
Have a look at how you are comparing String objects. You should use the equals method to compare a String's content. Using operators like == and != compares if the String objects are identical.
Now after using equals correctly have a look at how you are using nextLine. Check its Javadoc
I feel LineCounter(name) works because you did not put a ".txt" there. Try removing the ".txt" extension from the file name in the Filereader and Printwriter objects and see if it works. Usually in windows, the extension is not a part of the file name.
Here's an alternative (easier) solution to do what you want, using easier to understand code. (I think)
Also it avoids multiple
loops, but uses a single Java 8 stream to filter instead.
public static void deleteLine(String name, String line) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(name));
lines = lines.stream().filter(v -> !v.equals(line)).collect(Collectors.toList());
System.out.println(lines);
// if you want the String[] - but you don't need it
String[] linesAsStringArr = new String[lines.size()];
linesAsStringArr = lines.toArray(linesAsStringArr);
// write the file using our List<String>
Path out = Paths.get("output.txt"); // or another filename you dynamically create
Files.write(out, lines, Charset.forName("UTF-8"));
}

How to put Output in ArrayList from a file in Local

I am trying to segregate my data into multiple array list, so that I can use them later-on in my code. But I am not able to put my data in array list.
My code is about segregating the data into three array list of different Subjects (Example:Physics,chemistry) as per various filters, which you will find in my code.
Input data file:
1|150|20150328|20150406|Physics|1600|1600|2|68|92
2|152|20150328|20150406|Physics|1600|1500|2|68|89
3|153|20150328|20150406|Physics|1600|1500|2|68|60
4|155|20150328|20150406|Physics|1600|1600|2|68|72
5|161|20150328|20150406|Chemistry|1600|1600|2|68|77
Here's my code:
Public Class filter{
public static void main(String args[])
BufferedReader in= null;
BufferedWriter out= null;
String in_line;
String PrevRollNo= "";
int PrevDate= 0;
ArrayList<transaction> PhysicsList= new ArrayList<transaction>();
ArrayList<transaction> scList= new ArrayList<transaction>();
ArrayList<transaction> Chemistry= new ArrayList<transaction>();
try{
in = new BufferedReader(new FileReader(Path for input file));
File out_file= new File(Path for output file);
if(!out_file.exists())
{
(!out_file.createNewFile();
}
FileWriter fw=new FileWriter(out_file);
out= new BufferedWriter(fw);
while ((in_line=in.readline())!=null)
{
Transaction transact=new Transaction(in_line);
if(transact.RollNo.equals(PrevRollNo))
{
if(transact.subject.equals("Physics")&& transact.Prs_Date= PrevDate
{
PhysicsList.add(transact);
}
else if(transact.subject.equals("Physics")&&transact.wk_date != PrevDate}
Iterator<Transaction> it;
if(!transact.RoomNo.equals("102")&&!transact.lcl_RoomNo.equals("102");
{
it= scList.iterator();
while(it.hasnext())
{
Transaction sc= it.next();
if(sc.lcl_RoomNo.equals(transact.RoomNo) && sc.l1 equals(tansact.l1) && sc.l2 equals(transact.l2)
if(sc.marks==transact.marks)
{
transact.srsfound= true;
}
else
{
System.out.print.ln( "not found");
}
scList.remove(sc))
out.write(in_line);
break;
}}}}
Static Class Transaction
{
Public String RollNo, Subject, RoomNo, lcl_RoomNo, l1, l2;
Public int wk_date, prs_date;
Public double marks , amt;
Public boolean srcfound, tgtfound;
Public Transaction(String in_line)
{
String [] SplitData= in_line.split("\\|");
RollNo = SplitData[1];
Subject = SplitData[4]
RoomNo = SplitData[5];
lcl_RoomNo = SplitData[6];
l1 = SplitData[7];
l2 = SplitData[8];
wk_date = SplitData[3];
prs_date = SplitData[2];
marks = Double.parsedouble(SplitData[9]);
amt = Double.parsedouble(SplitData[]);
srcfound = false;
tgtfound = false;
}
Kindly help with your expertise.
Use Java 8 NIO and Streams. It will ease the job.
Files.lines(Paths.get("fileName.txt")).map(line -> {
String[] tokens = line.split("|");
//tokens contains individual elements of each line. Add your grouping logic on tokens array
}
I agree with the other answer in some ways. NIO should be used, it makes it a lot easier. However, I would avoid streams and instead use the readAllLines method like so:
try{
List<String> filecontents = new String(Files.readAllLines(file.toPath()); //file is the object to read from.
for(int i = 0; i < filecontents.size(); i++){
String line = lines.get(i);
//New code starts here
if(!line.contains("|") continue; //Ignore that line
//New code ends here
String[] array = line.split("|");
ArrayList<String> list = new ArrayList<String>();
for(int a = 0; a < array.length; a++){
String part = array[a];
list.add(part);
}
Transaction t = new Transaction(line);
if(line.contains("Physics") PlysicsList.add(t);
else if(line.contains("Chemistry") Chemistry.add(t);
else{ //Do nothing}
}
}catch(IOException e){
e.printStackTrace();
}
EDIT: I added a check in there. The reason the first and last lines may not be working is if the lines that are being parsed are not being parsed properly. See if this fixes your issue

Loading elements of Array into a collection

I have a text file of names( last and first). I have successfully been able to use RandomAccessFile class to load all the names into an Array of strings. What is left for me to do, is to assign each of the first names to an Array of first names and each of the last names in the list to an array of Last Names. Here is what I did but Im not getting any desired result.
public static void main(String[] args) {
String fname = "src\\workshop7\\customers.txt";
String s;
String[] Name;
String[] lastName, firstName;
String last, first;
RandomAccessFile f;
try {
f = new RandomAccessFile(fname, "r");
while ((s = f.readLine()) != null) {
Name = s.split("\\s");
System.out.println(Arrays.toString(Name));
for (int i = 0; i < Name.length; i++) {
first = Name[0];
last = Name[1];
System.out.println("last Name: " + last + "First Name: "+ first);
}
}
f.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
Please help me out I seem to be confused on what kind of collection to use and how to go about it Thanks
You could create a method to read a file and put the data in an Array, but, if you are determined to use an Array you are going to have to create it at a fixed size b/c arrays are immutable in java
public class tmp {
public static void main(String[] args) throws FileNotFoundException {
//problem you have to create an array of fixed size
String[] array = new String[4];
readLines(array);
}
public static String[] readLines(String[] lines) throws FileNotFoundException {
//this counter can be printed to check the size of your array
int count = 0; // number of array elements with data
// Create a File class object linked to the name of the file to read
java.io.File myFile = new java.io.File("path/to/file.txt");
// Create a Scanner named infile to read the input stream from the file
Scanner infile = new Scanner(myFile);
/* This while loop reads lines of text into an array. it uses a Scanner class
* boolean function hasNextLine() to see if there another line in the file.
*/
while (infile.hasNextLine()) {
// read a line and put it in an array element
lines[count] = infile.nextLine();
count++; // increment the number of array elements with data
} // end while
infile.close();
return lines;
}
}
However, the preferred method is to use an ArrayList which is an object that uses dynamically resizing arrays as data is added. In other words, you don't need to worry about having different size text files.
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("path/of/file.txt"));
String str;
ArrayList<String> list = new ArrayList<String>();
while ((str = in.readLine()) != null) {
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
A little about random access.
Classes like BufferedReader and FileInputStream use a sequential process of reading or writing data. RandomAccess, on the other hand, does exactly as the name implies, which is to permit non-sequential, random access to the contents of a file. However, Random access is typically used for other applications like reading and writing to zip files. Unless you have speed concerns I would recommend using the other classes.
public static void main(String[] args) throws FileNotFoundException {
BufferedReader in = new BufferedReader(new FileReader("src\\workshop7\\customers.txt"));
String str;
String names[];
List<String> firstName = new ArrayList();
List<String> lastName = new ArrayList();
try {
while ((str = in.readLine()) != null) {
names = str.split("\\s");
int count = 0;
do{
firstName.add(names[count]);
lastName.add(names[count+1]);
count = count + 2;
}while(count < names.length);
}
} catch (IOException e) {
e.printStackTrace();
}
// do whatever with firstName list here
System.out.println(firstName);
// do whatever with LastName list here
System.out.println(lastName);
}

How to merge data from two text file

I have two related text files shown for example in data1.txt and data2.txt. I want to merge the two files to create result.txt. Any idea how to go about this?
data1.txt
books, 3
Shelf, 5
groceries,6
books, 1
Shelf, 2
data2.txt
books,2
shelf,3
groceries,1
result.txt
books, 3, 2
Shelf, 5,3
groceries,6,1
books, 1,2
Shelf, 2, 3
this is a example for you.first you need to add values to 2d list from data2 text file.and then when line is null in file2 you can get mapping value relative to it's text from that list .so i have a method which will return back the mapping value for a String .code is little long than i thought .i post only relevant methods here.This is link to complete class file
public void marged(){
try {
BufferedReader br1 = null;
BufferedReader br2 = null;
String line1;
String line2;
ArrayList<ArrayList<String>> arrayList = new ArrayList<>();
br1 = new BufferedReader(new FileReader("C:\\Users\\Madhawa.se\\Desktop\\workingfox\\data1.txt"));
br2 = new BufferedReader(new FileReader("C:\\Users\\Madhawa.se\\Desktop\\workingfox\\data2.txt"));
while ((line1 = br1.readLine()) != null) {
String[] split1 = line1.split(",");
String line1word = split1[0].trim();
String line1val = split1[1].trim();
line2 = br2.readLine();
if (line2 != null) {
String[] split2 = line2.trim().split(",");
String line2word = split2[0].trim();
String line2val = split2[1].trim();
ArrayList<String> list = new ArrayList();
list.add(line2word);
list.add(line2val);
arrayList.add(list);
if (line1word.equalsIgnoreCase(line2word)) {
String ok = line1word + "," + line1val + "," + line2val;
System.out.println(ok);
}
} else {
String ok = line1word + "," + line1val + "," + doesexist(arrayList, line1word);
System.out.println(ok);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
this is the method return mapping value
public String doesexist(ArrayList<ArrayList<String>> arrayList, String s) {
for (int i = 0; i < arrayList.size(); i++) {
String get = arrayList.get(i).get(0);
if (get.trim().equalsIgnoreCase(s.trim())) {
return arrayList.get(i).get(1);
}
}
return "-1";
}
output>>
books,3,2
Shelf,5,3
groceries,6,1
books,1,2
Shelf,2,3
Simply add files into an array of File object then read it using loop.
File []files = new Files[amountOfFiles];
//initialize array elements
for(File f:files)
{
//read each file and store it into string variable
}
//finally write the string variable into result.txt file.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileNotFoundException;
public class SOQ21
{
public SOQ21()
{
merge();
}
public void merge()
{
try
{
String firstfile = "data1.txt";
FileReader fr1 = new FileReader(firstfile);
BufferedReader bfr1 = new BufferedReader(fr1);
String secondfile = "data2.txt";
FileReader fr2 = new FileReader(secondfile);
BufferedReader bfr2 = new BufferedReader(fr2);
/*
^^^ Right here is how you get the files and accompanying BufferedReaders
to handle them
*/
//next, using the readLine() method from the Java API, read each line
//for the first file
//then, separate by taking the words into an ArrayList and storing the
//numbers as Strings in a String[] of equal length of the ArrayList
//Do the same for the second file
//Then, if the word of ArrayList 1 matches the word of ArrayList 2,
//append the String numbers from String[] 2 to String[] 1
//DONE! :)
}
catch(FileNotFoundException ex)
{
//handle how you want
}
}
public static void main(String[] args)
{
SOQ21 soq = new SOQ21();
}
}
The comments I made should answer most of your questions. Lastly, I would pay special attention to the exceptions, I'm not entirely sure how you wanted to deal with that, but make sure you fill it with SOMETHING!

Java file read problem

I have a java problem. I am trying to read a txt file which has a variable number of integers per line, and for each line I need to sum every second integer! I am using scanner to read integers, but can't work out when a line is done. Can anyone help pls?
have a look at the BufferedReader class for reading a textfile and at the StringTokenizer class for splitting each line into strings.
String input;
BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
while ((input = br.readLine()) != null) {
input = input.trim();
StringTokenizer str = new StringTokenizer(input);
String text = str.nextToken(); //get your integers from this string
}
If I were you, I'd probably use FileUtils class from Apache Commons IO. The method readLines(File file) returns a List of Strings, one for each line. Then you can simply handle one line at a time.
Something like this:
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
for (String line : lines) {
// handle one line
}
(Unfortunately Commons IO doesn't support generics, so the there would be an unchecked assignment warning when assigning to List<String>. To remedy that use either #SuppressWarnings, or just an untyped List and casting to Strings.)
This is, perhaps, an example of a situation where one can apply "know and use the libraries" and skip writing some lower-level boilerplate code altogether.
or scrape from commons the essentials to both learn good technique and skip the jar:
import java.io.*;
import java.util.*;
class Test
{
public static void main(final String[] args)
{
File file = new File("Test.java");
BufferedReader buffreader = null;
String line = "";
ArrayList<String> list = new ArrayList<String>();
try
{
buffreader = new BufferedReader( new FileReader(file) );
line = buffreader.readLine();
while (line != null)
{
line = buffreader.readLine();
//do something with line or:
list.add(line);
}
} catch (IOException ioe)
{
// ignore
} finally
{
try
{
if (buffreader != null)
{
buffreader.close();
}
} catch (IOException ioe)
{
// ignore
}
}
//do something with list
for (String text : list)
{
// handle one line
System.out.println(text);
}
}
}
This is the solution that I would use.
import java.util.ArrayList;
import java.util.Scanner;
public class Solution1 {
public static void main(String[] args) throws IOException{
String nameFile;
File file;
Scanner keyboard = new Scanner(System.in);
int total = 0;
System.out.println("What is the name of the file");
nameFile = keyboard.nextLine();
file = new File(nameFile);
if(!file.exists()){
System.out.println("File does not exit");
System.exit(0);
}
Scanner reader = new Scanner(file);
while(reader.hasNext()){
String fileData = reader.nextLine();
for(int i = 0; i < fileData.length(); i++){
if(Character.isDigit(fileData.charAt(i))){
total = total + Integer.parseInt(fileData.charAt(i)+"");
}
}
System.out.println(total + " \n");
}
}
}

Categories

Resources