I'm trying to code a program that given a file with the names and addresses of five or more people, creates one different file (letter) for each of them (the new files will be named as the person who will receive it).
The structure of the main file is something like this:
type1.0001 #n John Harrison #a Whatever Street, 490 - Liverpool
.... and so on
So "type1" is the type of letter this person has to be sent, the words after "#n" are the name, and the words after "#a" the address.
What I've been trying is this:
String datos = "main_file.txt";
String tipo1 = "type1.txt";
String tipo2 = "type2.txt";
String tipo3 = "type3.txt";
char[] type1 = {'t', 'i', 'p', 'o', '1'};
//all other types should be here
String line;
FileReader fr = new FileReader("mainfile.txt");
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
while ((line = br.readLine()) != ".") {
char[] lineArray = line.toCharArray();
if (lineArray == type1) {
//code that creates file type1
}
}
}
fr.close();
So far this would just be the code that decides which letter to send, but it doesn't work.
I think it's something related to the "while" loop.
Please, I started Java 1 month ago, so if anyone could help me I'd be so grateful!
Thanks
Right now, I've got this:
FileReader fr = new FileReader("main_file.txt");
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
String nameMark = "#n";
String addressMark = "#a";
int nameStart = line.indexOf(nameMark) + nameMark.length();
int addressStart = line.indexOf(addressMark) + addressMark.length();
String name = line.substring(nameStart, addressStart - addressMark.length());
String address = line.substring(addressStart, line.length());
if (line.startsWith("tipo1.")) {
FileWriter fw = new FileWriter("file1.txt");
char[] vector = name.toCharArray();
int index = 0;
while (index < vector.length) {
fw.write(vector[index]);
index++;
}
fw.close();
} else if (line.startsWith("tipo2.")) {
FileWriter fw = new FileWriter("file1.txt");
char[] vector = name.toCharArray();
int index = 0;
while (index < vector.length) {
fw.write(vector[index]);
index++;
}
fw.close();
}
}
fr.close();
But it doesn't work.
Can someone help me out?
As Marc B told you, don't read the lines twice.
Also, just comparing the start of the line, will be much less overkill than you char array stuff.
To retrieve name and address, you could use indexOf and substring methods of String.
Here is a whole example :
while ((line = br.readLine()) != null) {
// get the name and the address of this line
String nameMark = "#n";
String addressMark = "#a";
int nameStart = line.indexOf(nameMark) + nameMark.length();
int addressStart = line.indexOf(addressMark) + addressMark.length();
String name = line.substring(nameStart, addressStart - addressMark.length());
String address = line.substring(addressStart, line.length());
// get the line type
if (line.startsWith("tipo1")) {
//code that creates file type1 with name and address
}
else if(line.startsWith("tipo2")) {
//code that creates file type2 with name and address
}
...
...
}
You can't use == with arrays. (Well, you can, but it doesn't do what you expect.) That is, this line is wrong:
if (lineArray == type1)
Try Arrays.equals instead:
if (Arrays.equals(lineArray, type1))
Try this for starters.
String line;
FileReader fr = new FileReader("mainfile.txt");
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) { // finish when line is null not "."
String [] parts = line.split("#");
String name, address;
if (parts.length > 2) {
name = parts[1].substring(2);
address = parts[2].substring(2);
}
if (line.startsWith("tipo1")) {
// save to tipo1 file
} else if (line.startsWith("tipo2")) {
// save to tipo2 file
} else if (line.startsWith("tipo2")) {
// save to tipo2 file
} else if (line.startsWith("tipo3")) {
// save to tipo2 file
} else if (line.startsWith("tipo4")) {
// save to tipo2 file
} else if (line.startsWith("tipo2")) {
// save to tipo2 file
}
}
fr.close();
Related
I have a text file and I need to check if it is correct. The file should be of the type:
XYab
XYab
XYab
Where X,Y,a,b can take only a certain range of value. For example b must be a value between 1 and 8. These values are defined by 4 enum (1 enum for X,1 enum for Y, etc..). The only thing that came to my mind is something like this:
BufferedReader br = new BufferedReader(new FileReader(FILENAME)
String s;
while ((s = br.readLine()) != null) {
if(s.charAt(0)==Enum.example.asChar())
}
But of course it checks only the first line of the file. Any advice on how I can check all the file's lines?
You could try something like this, (modify it according to yours enums)
#Test
public void findDates() {
File file = new File("pathToFile");
try{
Assert.assertTrue(validateFile(file));
}catch(Exception ex){
ex.printStackTrace();
}
}
private boolean validateFile(File file) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
// add yours enumns to one list
List<Enum> enums = new ArrayList<>();
enums.add(EnumX);
enums.add(EnumY);
enums.add(EnumA);
enums.add(EnumB);
while ((line = br.readLine()) != null) {
// process the line.
if(line.length() > 4){
return false;
}
//for each position check if the value is valid for the enum
for(int i = 0; i < 4; i++){
if(enums.get(i)).valueOf(line.charAt(i)) == null){
return false;
}
}
}
return true;
}
Don't forget about collision but if you have number or string you can use the regexp to do that.
On each Enum you have to do a function regexp like this. You can use an external Helper instead.
enum EnumX {
A,B,C,D, ...;
...
// you enum start to 0
public static String regexp(){
return "[0-" + EnumX.values().length +"]";
}
}
// it is working also if you have string in your file
enum EnumY{
A("toto"),B("titi"),C("tata"),D("loto");
public static String regexp(){
StringBuilder regexp = new StringBuilder("[");
for(EnumY value : EnumY.values()){
regexp.append(value).append(",");
}
regexp.replace(regexp.length()-1, regexp.length(), "]");
return regexp.toString();
}
}
public boolean isCorrect(File file){
// build the regexp
String regexp = EnumX.regexp() + EnumY.regexp() + EnumA.regexp() +EnumB.regexp();
// read the file
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if (line.matches(regexp) == false){
// this line is not correct
return false;
}
}
return true;
}
Here's the code:
FileReader fr = new FileReader("datos_clientes.txt");
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
String nameMark = "#n";
String addressMark = "#d";
int nameStart = line.indexOf(nameMark) + nameMark.length();
int addressStart = line.indexOf(addressMark) + addressMark.length();
String name = line.substring(nameStart, addressStart - addressMark.length());
String address = line.substring(addressStart, line.length());
if (line.startsWith("tipo1.")) {
FileWriter fw = new FileWriter(name +".txt");
char[] vector = name.toCharArray();
char[] vector2 = address.toCharArray();
int index = 0;
while (index < vector.length) {
fw.write(vector[index]+vector2[index]);
index++;
}
fw.close();
} else if (line.startsWith("tipo2.")) {
FileWriter fw = new FileWriter(name +".txt");
char[] vector = name.toCharArray();
char[] vector2 = address.toCharArray();
int index = 0;
while (index < vector.length) {
fw.write(vector[index]+vector2[index]);
index++;
}
fw.close();
}
else if (line.startsWith("tipo3.")) {
FileWriter fw = new FileWriter(name +".txt");
char[] vector = name.toCharArray();
char[] vector2 = address.toCharArray();
int index = 0;
while (index < vector.length) {
fw.write(vector[index]+vector2[index]);
index++;
}
fw.close();
}
}
What I want from this code is to create the each new file with the name of the recipient and their address.
The new files just show a combination of random alphabethical characters.
Then I have three pre-made files which I have to include in each new file so for example if one of the new files is "Maria Roberts.txt" and this person will receive a "type 1" letter I want the file (Maria Roberts.txt) to include the name, her address and the file "type1.txt"
I don't know how to do that.
I know I add things in every new question... sorry, I thing it will be easier for me to understand it.
Thanks again!
You're adding one character from the name array with one character from the address array, then outputting the result.
fw.write(vector[index]+vector2[index]);
Instead, you want to write the entire name array, then (in a different loop) write the entire address array.
int index = 0;
while (index < vector.length) {
fw.write(vector[index]);
index++;
}
index = 0;
while (index < vector2.length) {
fw.write(vector2[index]);
index++;
}
That will just stick them together, but you can use your imagination and figure out how to separate them the way you want.
I want the results from 'name' and 'code' to be inserted into log.txt file, but if I run this program only the name results gets inserted into .txt file, I cannot see code results appending under name. If I do System.outprintln(name) & System.outprintln(code) I get results printed in console but its not being inserted in a file.Can someone tell me what am I doing wrong?
Scanner sc = new Scanner(file, "UTF-8");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("text1")) {
String[] splits = line.split("=");
String name = splits[2];
for (int i = 0; i < name.length(); i++) {
out.println(name);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
String code = splits[2];
for (int i = 0; i < code.length(); i++) {
out.println(code);
}
}
out.close()
}
File looks like:
Name=111111111
Code=333,5555
Category-Warranty
Name=2222222
Code=111,22
Category-Warranty
Have a look at this code. Does that work for you?
final String NAME = "name";
final String CODE = "code";
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
String[] splits = line.split("=");
String key = splits[0];
String value = splits[1];
if (key.equals(NAME) || key.equals(CODE)) {
out.println(value);
}
}
out.close();
You have a couple of problems in your code:
you never actually assign the variables name and code.
you close() your PrintWriter inside the while-loop, that means you will have a problem if you read more than one line.
I don't see why this wouldn't work, without seeing more of what you are doing:
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("=")) {
if (line.contains("text1")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
}
}
out.flush();
out.close();
Make sure the second if condition is satisfied i.e. the line String contains "text2".
I want to write small java program to read data file first field and add seqcution number
Input file:
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Output file should be:
robert,190 vikign,...,0
robert,2401 windy,...,1
robert,1555 oakbrook,...,2
michell,2524 sprint,...,0
michell,1245 oakbrrok,...,1
xyz,2455 xyz drive,....,0
Check first field when value change sequction number start back to 0 otherwise add sequction number by 1
here is my code:
public static void createseq(String str) {
try {
BufferedReader br = null;
BufferedWriter bfAllBWP = null;
File folderall = new File("Sort_Data_File_Out");
File[] BFFileall = folderall.listFiles();
for (File file : BFFileall) {
br = new BufferedReader(new FileReader(file));
String bwp = "FinalDataFileOut\\" + str;
bfAllBWP = new BufferedWriter(new FileWriter(bwp));
String line;
line = br.readLine();
String[] actionID = line.split("\\|");
String fullname = actionID[0].trim();
int seq = 0;
String fullnameb;
while ((line = br.readLine()) != null) {
actionID = line.split("\\|");
fullnameb = actionID[0].trim();
if(fullname.equals(fullnameb)) {
seq++;
}
else {
System.out.println(line + "======" + seq + "\n");
seq = 0;
fullname = fullnameb;
}
System.out.println("dshgfsdj "+line + "======" + seq + "\n");
}
}
}
catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
The below code will fix the issue.I have updated the code if you face any pblm plz let me know :
Input :
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Code :
public static void createseq() {
try {
File file = new File("d:\\words.txt"); //Hardcoded file for testing locally
BufferedReader br = new BufferedReader(new FileReader(file));
HashMap<String,Integer> counter = new HashMap<String, Integer>();
String line;
while((line = br.readLine())!= null)
{
String[] actionID = line.split(",");
String firstName = actionID[0];
if(counter.containsKey(firstName))
{
counter.put(firstName, counter.get(firstName) + 1);
}
else
{
counter.put(firstName,0);
}
System.out.println(line+" "+counter.get(firstName));
}
br.close();
} catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
Ouput Come :
robert,190 vikign,... 0
robert,2401 windy,... 1
robert,1555 oakbrook,... 2
michell,2524 sprint,... 0
michell,1245 oakbrrok,... 1
xyz,2455 xyz drive,.... 0
I have a DB that usually generates a file with 3000 lines, actually I want to count the number of LAYERID(s)
My DB file is like this :
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE BUTYP=ACB8T,RAAT=FALSE,GBPATH=AAP4,GTXT=12;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_01,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_01,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_02,USFGN=DISABLED;
CREATE BUTYP=ACB9T,RAAT=TRUE,GBPATH=AAP4,GTXT=32;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_01,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_02,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_03,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_03,USFGN=DISABLED;
CREATE BUTYP=ACB2T,RAAT=TRUE,GBPATH=AAP4,GTXT=1;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE BUTYP=ACB8T,RAAT=FALSE,GBPATH=AAP4,GTXT=2;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE BUTYP=ACB8T,RAAT=TRUE,GBPATH=AAP4,GTXT=3;
if we just have "LAYID=LY_00" (like the first line) we must ignore it, but if under the "LAYID=LY_00" be "LAYID=LY_01 and ..." (like the third line) we must count "LAYID=LY_00" and others layerids,for example in line 3 till line 6 we have 4 Layeids
LAYID=LY_00
LAYID=LY_01
LAYID=LY_01
LAYID=LY_02
So count is 4 and if we want to count all of them we have 9, As I said before, if we just have
LAYID=LY_00 simillar line 1 we ignore it.
Also I wrote this method for read line by line :
public void execToken(File f) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
StringTokenizer strt = new StringTokenizer(line, ";");
while (strt.hasMoreTokens()) {
String token = strt.nextToken();
layerSupport(token);
}
}
}
and, I know the below method is not true and complete yet, but it's maybe useful for you
public void layerSupport(String token){
if(token.startsWith("CREATE TRMD") && !token.contains("LAYID=LY_00"))
System.out.println(token) ;
}
many thanks for your help ...
public int execToken(File f) throws Exception
{
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
int count = 0;
Pattern layID = Pattern.compile("LAYID=LY_\\d+");
Matcher matcher = null;
boolean isSingle = true;
while ((line = br.readLine()) != null)
{
if(line.contains("LAYID=LY_00"))
{
isSingle = false;
continue;
}
matcher = layID.matcher(line);
if(matcher.find())
{
count++;
if(!isSingle)
count++;
}
isSingle = true;
}
return count;
}
try this.it remembers if previous line contains LAYID=LY_00 and increments count twice in next iteration, if LAYID=LY_<digits> was found and isSingle is false.
Something like that:
public int execToken(File f) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(f));
int count = 0;
String line;
String previousLine = "";
while ((line = br.readLine()) != null) {
if (line.startsWith("CREATE TRMD")) {
if (!previousLine.isEmpty()) {
count += (previousLine.contains("LAYID=LY_00") ? 2 : 1);
}
previousLine = line;
} else {
previousLine = "";
}
}
return count;
}
Not tested.