I am trying to match file value with variable value. But somehow it is not matching. I checked it is reading file and holding value in the variable but not matching. Not sure if I have to use contains function.
int rcdMatch = 0;
String st;
String extdeductamt = "1000";
BufferedReader Br = null;
File objFile = new File(strPlanFile + NewFileNmae);
Br = new BufferedReader(new FileReader(objFile));
List < String > list = new ArrayList < String > ();
LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(objFile));
lineNumberReader.skip(Long.MAX_VALUE);
int lines = lineNumberReader.getLineNumber();
while ((st = Br.readLine()) != null) {
arraylist = st;
String amt = arraylist.substring(0, arraylist.length() - 392);
list.add(amt);
Set < String > unique = new HashSet < String > (list);
for (String key: unique) {
rcdMatch = 0;
if (key.trim().toString().equals(stvar)) {
String adjAmt = arraylist.substring(34, arraylist.length() - 348);
System.out.println("Adjustment Amount 1 is: " + adjAmt);
if (extdeductamt.trim().toString().equals(adjAmt.trim().toString())) {
rcdMatch++;
}
if (!(rcdMatch == 0)) {
System.out.println("PASS Amount is displayed: " + adjAmt);
}
}
break;
}
}
Related
CSV file
I am trying to save data separately by using ArrayList.
However, after saving one data into the array, it skips one line then saves the data. Please help me with this problem.
private void readCSVFile(String tickerCode, File file) {
System.out.println("Reading file " + tickerCode);
System.out.println(file.getPath());
try {
ArrayList<List<String>> line = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(file));
CSVReaderHeaderAware csvReader = new CSVReaderHeaderAware(br);
int numLine = 0;
String[] values;
while ((values = csvReader.readNext()) != null) {
ArrayList<String> data = new ArrayList<>();
data.add(values[0]);
data.add(values[1]);
data.add(values[2]);
data.add(values[3]);
data.add(values[4]);
data.add(values[5]);
data.add(values[6]);
line.add(data);
if(numLine == 0){
System.out.print("StartDate = "+ values[0]);
}
if((csvReader.readNext() == null)){
System.out.println(" EndDate = " + values[0]);
}
++numLine;
}
debugger variable
As mentioned in a comment, you cannot use csvReader.readNext() inside the loop as well to check if the next element is null, because it will actually read the next line. So what you can do is keep the last processed row's date in a variable, and then print it as the EndDate after the while loop is finished.
ArrayList<List<String>> line = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(file));
CSVReaderHeaderAware csvReader = new CSVReaderHeaderAware(br);
int numLine = 0;
String[] values;
String endDate = null;
while ((values = csvReader.readNext()) != null) {
ArrayList<String> data = new ArrayList<>();
data.add(values[0]);
data.add(values[1]);
data.add(values[2]);
data.add(values[3]);
data.add(values[4]);
data.add(values[5]);
data.add(values[6]);
line.add(data);
if(numLine == 0){
System.out.print("StartDate = "+ values[0]);
}
endDate = values[0];
++numLine;
}
if (endDate != null) { // Need to check null in case your CSV didn't have any rows
System.out.println(" EndDate = " + endDate);
}
I use Apache Tika to get encoding of file.
FileInputStream fis = new FileInputStream(my_file);
final AutoDetectReader detector = new AutoDetectReader(fis);
fis.close();
System.out.println("Encoding:" + detector.getCharset().toString());
I use Scanner to read values from file.
Scanner scanner = new Scanner(my_file, detector.getCharset().toString());
Map<String, String> values = new HashMap<>();
String line, key = null, value = null;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.contains(":")) {
if (key != null) {
values.put(key, value.trim());
key = null;
value = null;
}
int indexOfColon = line.indexOf(":");
key = line.substring(0, indexOfColon);
value = line.substring(indexOfColon + 1);
} else {
value += " " + line;
}
}
Scanner is unable to read text from files with encoding windows-1252, I get empty string.
UPDATE 2018.11.07.
I have same problem in case of BufferedReader.
Map<String, String> values = new HashMap<>();
String line, key = null, value = null;
FileInputStream is = new FileInputStream(my_file);
InputStreamReader isr = new InputStreamReader(is, getEncoding(my_file));
BufferedReader buffReader = new BufferedReader(isr);
while (buffReader.readLine() != null) {
line = buffReader.readLine();
if (line.contains(":")) {
if (key != null) {
values.put(key, value.trim());
key = null;
value = null;
}
int indexOfColon = line.indexOf(":");
key = line.substring(0, indexOfColon);
value = line.substring(indexOfColon + 1);
} else {
value += " " + line;
}
}
Instead of reading lines, I would try reading characters instead using the following approach:
ByteArrayOutputStream line = new ByteArrayOutputStream();
Scanner scanner = new Scanner(my_file);
while (scanner.hasNextInt()) {
int c = 0;
// read every line
while (c != newline) { // TODO: Check for a newline char
c = scanner.nextInt();
line.write((byte) c);
}
byte[] array = line.toByteArray();
String output = new String(array, "Windows-1252"); // This should do the trick
// We have a string here, do your logic
line.reset();
}
This approach is ugly, but uses new String which has the ability to specify a specific encoding. I did not test or run this code at all, but at least it will show you if any content is actually read properly.
I have to compare the two files having 50K records in each file.
The records are in text file but in following format :
Each line is having records.
If the records are same in both the files (comparing line by line) then we have to find the difference in corresponding records.
If the records are different (check at line 4) then increment the line in text file2 by one line and print this record of file2 as a new record not found in file1 and increment till it finds the record in file1 then compare the records in both lines.
Is this possible that we can compare the two files in this format.
EDIT
private void compareFiles(File sourceFile, File targetFile, XlxsDataUtility resultFile)
throws IOException {
FixedFormatManager manager = new FixedFormatManagerImpl();
FileInputStream fis = new FileInputStream(sourceFile);
DataInputStream dis = new DataInputStream(fis);
BufferedReader sourceReader = new BufferedReader(new InputStreamReader(dis));
String sourceLine;
FileInputStream fis2 = new FileInputStream(targetFile);
DataInputStream dis2 = new DataInputStream(fis2);
BufferedReader targetReader = new BufferedReader(new InputStreamReader(dis2));
String targetLine;
sourceReader.readLine();
targetReader.readLine();
StringBuilder stringBuilder = new StringBuilder();
StringBuilder differetLines = new StringBuilder();
int line = 1;
while ((sourceLine = sourceReader.readLine()) != null && (targetLine = targetReader.readLine()) != null) {
line++;
// here i have used fixedformatManger ancientprogramming api to parse the text.
Record1 record1 = manager.load(Record1.class, sourceLine);
Record2 record2 = manager.load(Record2.class, targetLine);
if (record1.getBlock().trim().equals(record2.getBlock().trim())
&& record1.getId().trim().equals(record2.getId().trim())) {
int minimum = Math.min(sourceLine.length(), targetLine.length());
int maximum = Math.max(sourceLine.length(), targetLine.length());
int index = 0;
String fromIndex = null;
String toIndex = null;
while (index < minimum) {
char sourceChar = sourceLine.charAt(index);
char targetChar = targetLine.charAt(index);
if (sourceChar != targetChar) {
stringBuilder.append(stringBuilder.length() > 0 ? ", " : "").append(index + 1).append(" - ");
while ((index < minimum) && (sourceChar != targetChar))
index++;
if (index == minimum) {
stringBuilder.append(maximum);
index = maximum;
} else {
stringBuilder.append(index);
}
index++;
resultFile.addRowData(record2.getId().trim(), String.valueOf(sourceChar),
String.valueOf(targetChar), stringBuilder.toString(), record1.getBlock(),
String.valueOf(line));
}
index++;
// resultFile.addRowData(stringBuilder.toString());
stringBuilder.delete(0, stringBuilder.length());
}
if (minimum != maximum && index < maximum) {
stringBuilder.append(stringBuilder.length() > 0 ? ", " : "").append(minimum + 1).append(" - ")
.append(maximum);
resultFile.addRowData(record1.getId().trim(), record2.getId().trim(), stringBuilder.toString(),
record1.getBlock(), String.valueOf(line));
stringBuilder.delete(0, stringBuilder.length());
}
// System.out.println(stringBuilder.toString());
} else {
// records in both lines are different
targetReader.readLine(); // I am not sure it works here or not
differetLines.append(record1.getBlock() + record1.getId().trim() + " is not found in "
+ record2.getBlock() + record2.getId().trim() + " at line Number :: " + line + "\n");
}
}
sourceReader.close();
targetReader.close();
writeDifferenceTofile(differetLines.toString(),"Flat_File New_Records");
}
}
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
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to print 2D Array from .txt file in Java
text file is:
8.00 28.00
18.00 28.00
8.00 23.00
12.00 20.00
15.00 30.00
... etc (many more lines)
i am reached upto:
public class Asgn2backup {
public static double[][] matrix;
public static void main(final String[] args) throws IOException {
System.out.print("Enter the name of the file: ");
final String fileName = readInput();
final BufferedReader br = new BufferedReader(
new FileReader(fileName + ".txt"));
String line;
int order = 0;
int rowIndex = 0;
int counter = 0;
while ((line = br.readLine()) != null) {
counter++;
if (counter == 1) {
order = Integer.parseInt(line);
matrix = new double[order][order];
System.out.println("order: " + order);
}
if (counter == 2) {
final String source = line;
System.out.println("source: " + source);
}
if (counter != 2 && counter != 1) {
order = Integer.parseInt(line);
matrix = new double[order][order];
System.out.println("order: " + order);
final StringTokenizer theLine =
new StringTokenizer(line, ", ");
int colIndex = 0;
while (theLine.hasMoreTokens()) {
final String st = theLine.nextToken();// .trim();
matrix[rowIndex][colIndex] = Double.parseDouble(st);
colIndex = colIndex + 1;
}
rowIndex = rowIndex + 1;
}
}
for (int x = 0; x < matrix.length - 1; x++) {
for (int p = 0; p < matrix.length - 1; p++) {
System.out.print(matrix[x][p] + " ");
}
}
br.close();
}
private static String readInput() {
try {
final BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
return in.readLine();
} catch (final IOException e) {
}
return "";
}
}
but it gives numberformatexception runtime error.
give me complete solution.
pls help me.
The parser does not fit the input file at all. In each condition you try to parse the entire line as a single integer value. This will cause NumberFormatExceptions.
Example:
if (counter != 2 && counter != 1) {
order = Integer.parseInt(line); // line = "8.00 23.00" < not an integer
The lines contain float or double values. So you'll have to split the line around multiple whitespaces and parse the two fragments with Double.parseDouble(split[<0|1>]) to double values.