Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
All - I am a newbie to java. So need some help or code
where the properties file is like
test.properties
100
200
300
400
I want to read it into an single array, so that the input data that I get, i can check if its within the array or not.
I could actually hard code the like if id=100 or id=200 or id=300 {then do somethings} else { do something ordo nothing} .
I was able to find the answer for it: Going to add the code here
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
public class read_properties_into_array {
private static List<String> sensitivePropertiesList=new ArrayList<String>();
public static void main(String[] args) {
try {
File file = new File("test.properties");
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInput);
fileInput.close();
Enumeration enuKeys = properties.keys();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
sensitivePropertiesList.add(new String(key));
//String value = properties.getProperty(key);
//System.out.println(key);
}
System.out.println("hi I am here");
System.out.println("lenght of list:"+sensitivePropertiesList.size());
for(int i=0;i<sensitivePropertiesList.size();i++)
{
System.out.println(sensitivePropertiesList.get(i));
}
System.out.println("Check if 100 it exists.");
if (sensitivePropertiesList.contains("100"))
{
System.out.println(" 100 it exists.");
}
else
{
System.out.println(" 100 Does not exist.");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please add the test.properties file at the java project level if using eclipse.
Test.properties
100
200
300
Though your question is not clear, I think you don't need a properties class to read an array from. You put key=value pairs in a properties file.
You should first read a file using java IO, then put all values in an array and finally iterate over that array and check for your value.
Check for some code here:
https://stackoverflow.com/a/7705672/841221
If you don't use a Java Properties file, but rather something like
test.properties
100
200
300
You could read all lines into a List and work later on that list.
Path inputFile = Paths.get("test.properties");
Charset fileCharset = Charset.defaultCharset();
List<String> allValues = Files.readAllLines(inputFile, fileCharset);
// work on that list
for (String value : allValues) {
System.out.println(value);
}
Related
This question already has answers here:
Multiple values in java.util.Properties
(5 answers)
Closed 2 years ago.
i have a file where i save one key with some entry (relation one to many).
From this file i need to extract values searching by key.
I just found a util (java.util.Properties) to handle properties files in Java.
It works very well for properties files.
But its return the first occurence for the key searched.
Since is present for properties files i expect that already exist also a version with multiple results allowed.
Exist a solution that returns an array of string for the researched key?
Properties is backed by a Hashtable so the key must be unique.
So if you want to stick to multiple instances of the same key you can implement the parsing yourself (if you don't depend too much on the extras managed by Properties):
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class FileInput {
Properties porp;
public static Map<String, List<String>> loadProperties(String file) throws IOException
{
HashMap<String, List<String>> multiMap = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("#"))
continue; // skip comment lines
String[] parts = line.split("=");
multiMap.computeIfAbsent(parts[0].trim(), k -> new ArrayList<String>()).add(parts[1].trim());
}
}
return multiMap;
}
public static void main(String[] args) throws IOException {
Map<String,List<String>> result=loadProperties("myproperties.properties");
}
}
UPDATED: improved exception handling (valid remark #rzwitsersloot). I prefer to throw the exception so the caller can decide what to do if the properties file is missing.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
While reading csv file data and storing large amount of records into mysql database by using JPA repository save() method. Not able to insert whole data only one record is updating in database. Suggest me where i am ding wrong.
private void readFileFromFile(FileUploadDetails fileUploadDetail) throws IOException {
String filePath = fileUploadDetail.getFilePath();
try {
FileReader filereader = new FileReader(filePath);
CSVReader csvReader = new CSVReaderBuilder(filereader).withSkipLines(1).build();
List<String[]> nextRecord;
List<FileAnnualEnterpriseSurveyLog> fileAnnualEnterpriseSurveyLog = new ArrayList<>();
FileAnnualEnterpriseSurveyLog fileAESurveyLogVo = new FileAnnualEnterpriseSurveyLog();
// we are going to read data line by line
List<String[]> allData = csvReader.readAll();
int count = 0;
for (String[] cell : allData) {
fileAESurveyLogVo.setYear(cell[0].toString());
fileAESurveyLogVo.setIndustryAggregationNZSIOC(cell[1].toString());
fileAESurveyLogVo.setIndustryCodeNZSIOC(cell[2].toString());
fileAESurveyLogVo.setIndustryNameNZSIOC(cell[3].toString());
fileAESurveyLogVo.setUnits(cell[4].toString());
fileAESurveyLogVo.setVariableCode(cell[5].toString());
fileAESurveyLogVo.setVariableName(cell[6].toString());
fileAESurveyLogVo.setVariableCategory(cell[7].toString());
fileAESurveyLogVo.setValue(cell[8].toString());
fileAESurveyLogVo.setIndustryCodeANZSIC06(cell[9].toString());
fileAnnualEnterpriseSurveyLog.add(fileAESurveyLogVo);
// fileAnnualEnterpriseSurveyRepository.save(fileAESurveyLogVo);
// fileAnnualEnterpriseSurveyRepository.
System.out.println(count);
count++;
}
System.out.println(fileAnnualEnterpriseSurveyLog.size()); // 277777
for (FileAnnualEnterpriseSurveyLog file : fileAnnualEnterpriseSurveyLog) {
fileAnnualEnterpriseSurveyRepository.save(file);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
After you have inserted the first object, you are updating always the same. You should create a new element at each iteration.
for (String[] cell : allData) {
fileAESurveyLogVo = new FileAnnualEnterpriseSurveyLog();
fileAESurveyLogVo.setYear(cell[0].toString());
fileAESurveyLogVo.setIndustryAggregationNZSIOC(cell[1].toString());
... etc ...
}
Here's the deal :
I was asked to developp a JAVA program that would do some reorganisations of .tsv files (moving cells to do some kind of transposition).
So, I tried to do it cleanly and got now 3 different packages:
.
Only tsvExceptions and tsvTranspositer are needed to make the main (TSVTransposer.java) work.
Yesterday I learned that I would have to implement it in Talend myself which I had never heard of.
So by searching, i stepped on this stackOverflow topic. So i followed the steps, creating a routine, copy/pasting my main inside it (changing the package to "routines") and added the external needed libraries to it (my two packages exported as jar files and openCSV). Now, when I open the routine, no error is showned but I can't drag & drop it to my created job !
Nothing happens. It just opens the component infos as shown with "Properties not available."
package routines;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import tsvExceptions.ArgsExceptions;
import tsvExceptions.EmptyArgsException;
import tsvExceptions.OutOfBordersArgsException;
import tsvTranspositer.CommonLine;
import tsvTranspositer.HeadOfValuesHandler;
import tsvTranspositer.InputFile;
import tsvTranspositer.OutputFile;
public class tsvRoutine {
public static void main(String[] args) throws ArgsExceptions {
// Boolean set to true while everything is good
Boolean everythingOk = true;
String inputFile = null; // Name of the entry file to be transposed.
String outputFile = null; // Name of the output file.
int serieNb = 1 ; // Number of columns before the actual values in the input file. Can be columns describing the product as well as empty columns before the values.
int linesToCopy = 0; // Number of lines composing the header of the file (those lines will be copy/pasted in the output)
/*
* Handling the arguments first.
*/
try {
switch (args.length) {
case 0:
throw new EmptyArgsException();
case 1:
inputFile = args[0];
String[] parts = inputFile.split("\\.");
// If no outPutFile name is given, will add "Transposed" to the inputFile Name
outputFile = parts[0] + "Transposed." + parts[1];
break;
case 2:
inputFile = args[0];
outputFile = args[1];
break;
case 3:
inputFile = args[0];
outputFile = args[1];
serieNb = Integer.parseInt(args[2]);
break;
case 4:
inputFile = args[0];
outputFile = args[1];
serieNb = Integer.parseInt(args[2]);
linesToCopy = Integer.parseInt(args[3]);
break;
default:
inputFile = args[0];
outputFile = args[1];
serieNb = Integer.parseInt(args[2]);
linesToCopy = Integer.parseInt(args[3]);
throw new OutOfBordersArgsException();
}
}
catch (ArgsExceptions a) {
a.notOk(everythingOk);
}
catch (NumberFormatException n) {
System.out.println("Arguments 3 & 4 should be numbers."
+ " Number 3 is the Number of columns before the actual values in the input file. \n"
+ "(Can be columns describing the product as well as empty columns before the values. (1 by default)) \n"
+ "Number 4 is the number of lines to copy/pasta. (0 by default) \n"
+ "Please try again.");
everythingOk = false;
}
// Creating an InputFile and an OutputFile
InputFile ex1 = new InputFile(inputFile, linesToCopy);
OutputFile ex2 = new OutputFile(outputFile);
if (everythingOk) {
try ( FileReader fr = new FileReader(inputFile);
CSVReader reader = new CSVReader(fr, '\t', '\'', 0);
FileWriter fw = new FileWriter(outputFile);
CSVWriter writer = new CSVWriter(fw, '\t', CSVWriter.NO_QUOTE_CHARACTER))
{
ex1.setReader(reader);
ex2.setWriter(writer);
// Reading the header of the file
ex1.readHead();
// Writing the header of the file (copy/pasta)
ex2.write(ex1.getHeadFile());
// Handling the line containing the columns names
HeadOfValuesHandler handler = new HeadOfValuesHandler(ex1.readLine(), serieNb);
ex2.writeLine(handler.createOutputHOV());
// Each lien will be read and written (in multiple lines) one after the other.
String[] row;
CommonLine cl1;
// If the period is monthly
if (handler.isMonthly()) {
while (!ex1.isAllDone()) {
row = ex1.readLine();
if (!ex1.isAllDone()) {
cl1 = new CommonLine(row, handler.getYears(), handler.getMonths(), serieNb);
ex2.write(cl1.exportOutputLines());
}
}
}
// If the period is yearly
else {
while (!ex1.isAllDone()) {
row = ex1.readLine();
if (!ex1.isAllDone()) {
cl1 = new CommonLine(row, handler.getYears(), serieNb);
ex2.write(cl1.exportOutputLines());
}
}
}
}
catch (FileNotFoundException f) {
System.out.println(inputFile + " can't be found. Cancelling...");
}
catch (IOException e) {
System.out.println("Unknown exception raised.");
e.printStackTrace();
}
}
}
}
I know the exceptions aren't correctly handled yet, but they are in some kind of hurry for it to work in some way.
Another problem that will occur later is that I have no idea how to parse arguments to the program that are required.
Anyway, thanks for reading this post!
You cannot add routines per drag and drop to a job. You will need to access the routines functions through components.
For example, you would start with a tFileListInput to get all files you need. Then you could add a tFileInputDelimited where you describe all fields of your input. After this, with e.g. a tJavaRow component, you can write some code which would access your routine.
NOTE: Keep in mind that Talend works usually row-wise. This means that your routines should handle stuff in a row-wise manner. This could also mean that your code has to be refactored accordingly. A main function won't work, this has at least to become a class which can be instanciated or has static functions.
If you want to handle everything on your own, instead of a tJavaRow component you might use a tJava component which adds more flexibility.
Still, it won't be as easy as simply adding the routine and everything will work.
In fact, the whole code can become a job on its own. Talend generates the whole Java code for you:
The parameters can become Context variables.
The check if numbers are numbers could be done several ways, for example with a tPreJob and a tJava
Input file could be connected with a tFileInputDelimited with a dot separator
Then, every row will be processed with either a tJavaRow with your custom code or with a tMap if its not too complex.
Afterwards, you can write the file with a tFileOutputDelimited component
Everything will get connected via right click / main to iterate over the rows
All exception handling is done by Talend. If you want to react to exceptions, you can use a component like tLogRow.
Hope this helps a bit to set the direction.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
At the moment I'm making a HangMan GUI game in Java. It works when I put the words right into the program.
But now I want to load a textfile and create a string of it, in the code below the string content.
Here on StackOverflow I have read about the use of scanners.
Now I have this code, but it won't accept the File file = new File("woordenlijst.txt"); statement, it says at 'File' that it cannot find symbol. Can you help me? this is my code:
import java.util.Scanner;
public class galgjeGUI extends javax.swing.JFrame {
/**
* Creates new form galgjeGUI
*/
private String wGalg; // het te raden woord
private int fouten; // globale variabele toegevoegd jonp
private int pogingen;
private int levens = 7;
public galgjeGUI() {
initComponents();
buttonDisableFunction();
File file = new File("woordenlijst.txt");
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
}
how does java know what you mean by File, there is no class called File, you are looking for java.io.File so tell compiler to use that by adding
import java.io.File;
1) Import proper packages.
2) Handle exceptions.
3) close() Scanner object after usage.
import java.io.*; //import
Scanner scan = null;
try { //handle exceptions
File file = new File("woordenlijst.txt");
scan = new Scanner(file);
}
catch(FileNotFoundException e) {
System.out.println(e);
}
finally {
scan.close(); // give up the resource.
}
Content of data.txt file
pin=9876
balance=9001
investment=10000
interest=0.065
isLockedOut=false
My code currently:
import java.io.*;
import java.util.Properties;
public class SetData extends ATM {
public static void setIsLockedOut(boolean isLockedOut) { //Sets the isLockedOut variable
try {
Properties data = new Properties();
FileOutputStream output = new FileOutputStream("data.txt");
if (isLockedOut = true) {
data.setProperty("isLockedOut", "true");
data.store(output, null);
output.close(); //Closes the output stream
}
else {
data.setProperty("isLockedOut", "false");
data.store(output, null);
output.close();
}
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
I have also checked and referred to a similar question on StackOverflow as well (Updating property value in properties file without deleting other values).
The method 'setIsLockedOut' is called from another class.
When I call this method to set the 'isLockedOut' variable to true in the 'data.txt' file, all other variables are erased except the 'isLockedOut' variable. This is the output:
#Sun Nov 17 15:44:42 EST 2013
isLockedOut=true
So my question is, how can I update a property value without erasing the other values in the file?
All you are doing is overwriting the data.txt file with the content of data which is just the value of "isLockedOut". It seems that what you want to do is to overwrite data.txt with all of the properties that used to be in data.txt, plus an updated value for "isLockedOut". To do that, you need to open data.txt for reading and read its content into data, then modify data, then overwrite data.txt with the new data. Skipping the first step is what is causing your problem.
You need to use a FileInputStream and the load method. Use them much the same way you are using FileOutputStream and store already.