My Java program has a superclass (ProgettoBase) and two underclasses (ProgettoCorpo and ProgettoOre). I must copy two different csv files (progetti_ora.csv and progetti_corpo.csv) to a list but I can't see the elements of the list when I launch the program.
public void readFile () {
List<String> projects = new ArrayList<>();
System.out.println("My list is: " + projects);
//read 1 progetti_ora
String csvFile = "progetti_ora.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
//read 2 progetti_corpo
String csvFileDue = "progetti_corpo.csv";
BufferedReader brDue = null;
String lineDue = "";
String cvsSplitByDue = ";";
//read file 1
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] vote = line.split(cvsSplitBy);
for(String s : vote)
System.out.println("List one: " + s);
for(int x = 0; x <= 2; x++) {
projects.add(vote[x].toString());
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("OK1");
//read file 2
try {
brDue = new BufferedReader(new FileReader(csvFileDue));
while ((lineDue = brDue.readLine()) != null) {
String[] voteDue = lineDue.split(cvsSplitByDue);
for(String t : voteDue)
System.out.println("Lista file due: " + t);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println("OK2");
}
Related
I have a file with this content:
1.10.100.1 1000.0
1.10.100.2 2000.0
1.10.100.3 2000.0
1.10.500.4 1000.0
i wrote the function that find the specific string in the file:
public double searchInBalance(String depositNumber) {
try {
String[] words = null;
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String string;
String inputBalanceToFind = depositNumber;
while ((string = bufferedReader.readLine()) != null) {
words = string.split(" ");
for (String word : words) {
if (word.equals(inputBalanceToFind)) {
System.out.println("string :" + string);
}
}
}
fileReader.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in searchInBalance");
}
return 1;
}
i want to make a function that when find the left value of the file return the right value(the double value) back but have no idea how to do that please help me
public double searchInBalance(String depositNumber){
try {
String[] words = null;
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String string;
String inputBalanceToFind = depositNumber;
while ((string = bufferedReader.readLine()) != null) {
words = string.split(" ");
for (int i = 1; i < words.length; i += 2) {
if (words[i].equals(inputBalanceToFind)) {
System.out.println(words[i]+" - "+words[i - 1]);
}
}
}
fileReader.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in searchInBalance");
}
}
Just make a for loop with a counter to work with the indexes of the Array. But this is not a good programming style and you should try to improve your solution :D
copy part like this(from date to date) I am trying to copy only a part of .CSV file based on the first column (Start Date and Time) data looks like (2019-01-28 10:22:00 AM) but the user have to put it like this (2019/01/28 10:22:00)
this is for windows, java opencsv , this is what I found but dont do what I need exaclty :
like this:
int startLine = get value1 from column csv ;
int endLine = get value2 from column csv;
public static void showLines(String fileName, int startLine, int endLine) throws IOException {
String line = null;
int currentLineNo = 1;
// int startLine = 20056;//40930;
// int currentLineNo = 0;
File currentDirectory = new File(new File(".").getAbsolutePath());
String fromPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
PrintWriter pw = null;
pw = new PrintWriter(new FileOutputStream(fromPath), true);
//pw.close();
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read to startLine
while(currentLineNo<startLine) {
if (in.readLine()==null) {
// oops, early end of file
throw new IOException("File too small");
}
currentLineNo++;
}
//read until endLine
while(currentLineNo<=endLine) {
line = in.readLine();
if (line==null) {
// here, we'll forgive a short file
// note finally still cleans up
return;
}
System.out.println(line);
currentLineNo++;
pw.println(line);
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
}finally {
try { if (in!=null) in.close();
pw.close();
} catch(IOException ignore) {}
}
}
public static void main(String[] args) throws FileNotFoundException {
int startLine = 17 ;
int endLine = 2222;
File currentDirectory = new File(new File(".").getAbsolutePath());
try {
showLines(currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv", startLine, endLine);
} catch (IOException e) {
e.printStackTrace();
}
// pw.println();
}
Common CSV format uses a comma as a delimiter, with quotations used to escape any column entry that uses them within the data. Assuming that your column one data is consistent with the format you posted, and that I wouldn't have to bother with quotations marks therefor, you could read the columns as:
public static void main(String[] args) {
//This is the path to the file you are writing to
String targetPath = "";
//This is the path to the file you are reading from
String inputFilePath = "";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/01/28 10:30:00";
String addFlagSplit[] = startLine.replace("/", "-").split(" ");
String addFlag = addFlagSplit[0] + " " + addFlagSplit[1];
String endFlagSplit[] = endLine.replace("/", "-").split(" ");
String endFlag = endFlagSplit[0] + " " + endFlagSplit[1];
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(addFlag)) {
add = true;
}else if(date.contains(endFlag)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
File currentDirectory = new File(new File(".").getAbsolutePath());
String targetPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
String inputFilePath = currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/04/06 10:30:00";
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(startLine)) {
add = true;
}else if(date.contains(endLine)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
I want to search the specific word in the text file and store that word in the array list. I have done like this but it gives output like word exist in the text file or not. I want to store that text in the array list
double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = "";
String filePath = "D:\\PDFTOEXCEL\\Extractionfrompdf.txt";
BufferedReader br;
String inputSearch = "Facture";
String line = "";
try {
br = new BufferedReader(new FileReader(filePath));
try {
while ((line = br.readLine()) != null) {
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(inputSearch)) {
count++;
countBuffer++;
}
}
if (countBuffer > 0) {
countBuffer = 0;
lineNumber += countLine + ",";
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = "";
String filePath = "D:\\PDFTOEXCEL\\Extractionfrompdf.txt";
BufferedReader br;
String inputSearch = "Facture";
String line = "";
List<String> searchedWords = new ArrayList<>();
try {
br = new BufferedReader(new FileReader(filePath));
try {
while ((line = br.readLine()) != null) {
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(inputSearch)) {
count++;
countBuffer++;
if(!searchedWords.contains(word)){
searchedWords.add(word);
}
}
}
if (countBuffer > 0) {
countBuffer = 0;
lineNumber += countLine + ",";
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("Words that you have searched and found:");
for(String word : searchedWords){
System.out.println(word);
}
You will have an arraylist searchedWords which will keep track of the searched words, you will notice that the if statement will not allow duplicates in the arraylist, so if you want to allow duplicates just remove the if(!searchedWords.contains(word)) and just write searchedWords.add(word);.
You can define a String ArrayList with your other declarations using:
ArrayList<String> matches = new ArrayList<String>();
Then when you find a word that matches, add it to the ArrayList using:
matches.add(word);
Edit:
double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = "";
String filePath = "D:\\PDFTOEXCEL\\Extractionfrompdf.txt";
BufferedReader br;
String inputSearch = "Facture";
String line = "";
ArrayList<String> matches = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(filePath));
try {
while ((line = br.readLine()) != null) {
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(inputSearch)) {
count++;
countBuffer++;
matches.add(word);
}
}
if (countBuffer > 0) {
countBuffer = 0;
lineNumber += countLine + ",";
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I am traversing to the below location to the properties file : "global.properties"
String currentPath = System.getProperty("user.dir");
File appPropDir = new File(currentPath, "properties");
File app_prop_file = new File(appPropDir, "global.properties");
After making changes to a particular parameter in "global.properties", I want to know how to upload the file to the same location. For instance, here I am appending the "propFileName" to the end of property : product + ".app.product.types". After making this append, how to upload the file "global.properties" to the user.dir
Entire code :
public static synchronized void updateGlobalPropFile(String product_name, String file_name) throws Exception {
// logger.debug("Entry-->
// com.manh.ci.eaas.util.TemplateUtil.updateGlobalPropFile");
System.out.println("in updateGlobalPropFile");
String downloadLoc = "";
String mmcType;
String vers;
String box, userId, password, location, key;
int port;
port = 22;
String currentPath = System.getProperty("user.dir");
File appPropDir = new File(currentPath, "properties");
File app_prop_file = new File(appPropDir, "global.properties");
downloadLoc = app_prop_file.toString();
port = Integer.parseInt(prop.getProperty("ssh_connection_port"));
port = 22;
String product = product_name;
String file = file_name;
String propFileName = "file";
String changeKey = product + ".app.product.types";
System.out.println("changeKey>>" + changeKey);
// download global.properties instead of using local copy
String globalPropFileLoc = downloadLoc;
try (BufferedReader br =
new BufferedReader(new InputStreamReader(new FileInputStream(new File(globalPropFileLoc))))) {
ArrayList<String> lines = new ArrayList<String>();
String line = "";
String tempLine = "";
while ((line = br.readLine()) != null) {
if (line.startsWith(changeKey) && line.contains(changeKey) &&
(line.substring(0, changeKey.length()).equals(changeKey))) {
String strChangeKey = line.substring(changeKey.length() + 1);
// System.out.println("strChangeKey>>"+strChangeKey);
if (strChangeKey.equalsIgnoreCase("") || strChangeKey.equalsIgnoreCase(" ")) {
// chek if value after = is empty for a newly added changekey : don't add comma
// for first value
tempLine = line + propFileName;
} else {
tempLine = line + "," + propFileName;
}
} else {
tempLine = line;
}
lines.add(tempLine);
}
if (lines.size() != 0) {
BufferedWriter out = new BufferedWriter(new FileWriter(new File(globalPropFileLoc)));
String finalStr = "";
for (int i = 0; i < lines.size(); i++) {
finalStr = finalStr + lines.get(i) + "\n";
}
out.write(finalStr);
System.out.println("updated global prop file");
out.close();
}
uploadFile();
} catch (Exception e) {
// logger.debug(e);
e.printStackTrace();
throw e;
}
}
Just help me with the uploadFile(); in the above code. Thanks a lot.
This should do the trick:
public void uploadFile(final List<String> lines, final String targetFilePath) throws IOException {
Files.write(Paths.get(targetFilePath), lines);
}
i am trying to use this code to replace field and after the replace is done i like to delete the file. But when i replace the file only 1 line was saved. How should i ensure that the other lines will be saved?
public static void main(String[] args){
AddChips();
}
public static void AddChips() {
File oldFile = new File ("players.dat");
File newFile = new File ("tempchips.dat");
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> player = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(oldFile));
bw = new BufferedWriter(new FileWriter(newFile));
String line;
Scanner read = new Scanner(System.in);
System.out.println("Please Enter Username");
String UserN = read.nextLine();
System.out.println("Please Enter Chips to Add");
String UserCadd = read.nextLine();
while ((line = br.readLine()) != null) {
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
int totalChips = (Integer.parseInt(UserCadd)+ Integer.parseInt(Chips));
if (Username.equals(UserN)){
line = Username + "|" + Password + "|" + totalChips;
bw.write(line + System.getProperty("line.separator"));
}
//issue is here
br.close();
bw.close();
oldFile.delete();
newFile.renameTo(oldFile);
//AdminMenu();
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
}