Let's assume we have a text file like this one:
#this is a config file for John's server
MAX_CLIENT=100
# changed by Mary
TCP_PORT = 9000
And I have written the following code :
this.reader = new BufferedReader(new FileReader(filename));
String line;
line = reader.readLine();
while (line.length() != 0) {
line = line.trim();
if (line.contains("#") || line.contains("")) {
line = reader.readLine();
} else {
if (line.contains("MAX_CLIENT=")) {
line = line.replace("MAX_CLIENT=", "");
this.clientmax = Integer.parseInt(line);
}
if (line.contains("TCP_PORT=")) {
line = line.replace("TCP_Port=", "");
tcp_port = Integer.parseInt(line);
}
}
}
where clientmax and tcp_port are of type int.
Will clientmax and tcp_port receive their value for this code?
What should I do if I the text file changes a little bit to:
MAX_CLIENT=100# changed by Mary
containing a comment after the number.
ow,btw # represents the start of a comment.
Thank you.
You should use a class designed for this purpose: Properties
This class handles comments for you so you don't have to worry about them.
You use it like this:
Properties prop = new Properties();
prop.load(new FileInputStream(filename));
Then you can extract properties form it using:
tcpPort = Integer.parseInt(prop.getProperty("tcpPort"));
Or save using:
prop.setProperty("tcpPort", String.valueOf(tcpPort));
Use line.startsWith("#") instead of line.contains("#")
When you do this, keep in mind that you need to stop reading when you reach a comment character.
Related
I have ini file that to be read in my application but the problem is it is not reading the entire file and it stucks in the while loop.
My code:
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
Properties section = null;
while(line!=null){
if(line.startsWith("[") && line.endsWith("]")){
section = new Properties();
this.config.put(line.substring(1, line.length() - 1), section);
}else{
String key = line.split("=")[0];
String value = line.split("=")[1];
section.setProperty(key, value);
}
line = br.readLine();
System.out.println(line);
// To continue reading newline.
//if i remove this, it will not continue reading the second header
if(line.equals("")){
line = br.readLine();
}
}
System.out.println("Done"); // Not printing this.
This is what inside the ini file. The newlines are included so I add if the line.equals("").
[header]
key=value
[header2]
key1=value1
key2=value2
[header3]
key=value
// -- stops here
//this newlines are included.
#Some text // stops here when I remove all the newlines in the ini file.
#Some text
Output:
[header]
key=value
[header2]
key1=value1
key2=value2
[header3]
key=value
//whitespace
//whitespace
UPDATE:
I remove all the newlines in the ini file but still not reading the entire file.
Unless there's something you've not included in this post the logic won't get stuck in the loop... If the file you're using looks exactly like what you've posted, it'll hit either a blank line(because you're only skipping 1 blank) or one of the lines starting "#" and get an ArrayIndexOutOfBoundsException because those lines don't contain an "="... Simplify your while loop to this and the ArrayIndexOutOfBoundsExceptions wont occur and it'll process the full file:
Properties section = null;
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("[") && line.endsWith("]")) {
section = new Properties();
this.config.put(line.substring(1, line.length() - 1), section);
} else if (line.contains("=") && !line.startsWith("#")) {
String[] keyValue = line.split("=");
section.setProperty(keyValue[0], keyValue[1]);
}
}
Notice that I'm doing a line.contains("=") so that blank lines and lines beginning # are skipped over...
Can someone tell me how to read every second line from a file in java?
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while(line != null){
//Do something ..
line = br.readLine()
}
br.close
One simple way would be to just maintain a counter of number of lines read:
int count = 0;
String line;
while ((line = br.readLine()) != null) {
if (count % 2 == 0) {
// do something with this line
}
++count;
}
But this still technically reads every line in the file, only choosing to process every other line. If you really only want to read every second line, then something like RandomAccessFile might be necessary.
You can do it in Java 8 fashion with very few lines :
static final int FIRST_LINE = 1;
Stream<String> lines = Files.lines(path);
String secondLine = lines.limit(2).skip(FIST_LINE).collect(Collectors.joining("\n"));
First you stream your file lines
You keep only the two first lines
Skip the first line
Note : In java 8, when using Files.lines(), you are supposed to close the stream afterwards or use it in a try-with-resource block.
This is similar to #Tim Biegeleisen's approach, but I thought I would show an alternative to get every other line using a boolean instead of a counter:
boolean skipOddLine = true;
String line;
while ((line = br.readLine()) != null) {
if (skipOddLine = !skipOddLine) {
//Use the String line here
}
}
This will toggle the boolean value every loop iteration, skipping every odd line. If you want to skip every even line instead you just need to change the initial condition to boolean skipOddLine = false;.
Note: This approach only works if you do not need to extend functionality to skip every 3rd line for example, where an approach like Tim's would be easier to modify. It also has the downside of being harder to read than the modulo approach.
This will help you to do it very well
You can use try with resource
You can use stream api java 8
You can use stream api supplier to use stream object again and again
I already hane added comment area to understand you
try (BufferedReader reader =
new BufferedReader(
new InputStreamReader(
new ByteArrayInputStream(x.getBytes()),
"UTF-8"))) { //this will help to you for various languages reading files
Supplier<Stream<String>> fileContentStream = reader::lines; // this will help you to use stream object again and again
if (FilenameUtils.getExtension(x.getOriginalFilename()).equals("txt")) { this will help you to various files extension filter
String secondLine = lines.limit(2).skip(FIST_LINE).collect(Collectors.joining("\n"));
String secondLine =
fileContentStream
.get()
.limit(2)
.skip(1)// you can skip any line with this action
.collect(Collectors.joining("\n"));
}
else if (FilenameUtils.getExtension(x.getOriginalFilename()).equals("pdf")) {
} catch (Exception ex) {
}
i am writing a java program to read a file and print output to another string variable.which is working perfectly as intended using is code.
{
String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null) {
key += line;
line = reader.readLine();
}
System.out.println(key); //this prints contents of .txt file
}
this prints whole text in the file.But i want to only print the lines till word END is encountered in file.
example: if input.txt file contains following text : this test file END extra in
it should print only :
this test file
Just do a simple indexOf to see where it is and if it exists in the line. If the instance is found one option would be using substring to cut off everything up until the index of the keyword. For a bit more control though try using java regular expressions.
String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while ((line = reader.readLine()) != null && line.indexOf("Keyword to look for") == -1)
key += line;
System.out.println(key);
I am not sure why it needs to be any more complicated than this:
BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str = re.readLine();
if (str.equals("exit")) break;
// whatever other code.
}
You can do it in many ways. one of them is using indexOf method to specify the start index of "END" in input and then using subString method.
for more information, read documentation of String calss. HERE
This will work for your issue.
public static void main(String[] args) throws IOException {
String key = "";
FileReader file = new FileReader("/home/halil/khalil.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null) {
key += line;
line = reader.readLine();
} String output = "";
if(key.contains("END")) {
output = key.split("END")[0];
System.out.println(output);
}
}
You have to change your logic to check if the line contains "END".
If END not found in a line, add the line to key stringin your program
If yes, split that line into word array, read the line till you encounter the word "END" and append it to your key string. Consider using Stringbuilder for key.
while (line != null) {
line = reader.readLine();
if(!line.contains("END")){
key += line;
}else{
//Note that you can use split logic like below, or use java substring
String[] words = line.split("");
for(String s : words){
if(s.equals("END")){
return key;
}
key += s;
}
}
}
I have created a method with BufferedReader that opens a text file created previously by the program and extracts some characters. My problem is that it extracts the whole line and I want to extract only after a specified character, the :.
Here is my try/catch block:
try {
InputStream ips = new FileInputStream("file.txt");
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br1 = new BufferedReader(ipsr);
String ligne;
while((ligne = br1.readLine()) != null) {
if(ligne.startsWith("Identifiant: ")) {
System.out.println(ligne);
id = ligne;
}
if(ligne.startsWith("Pass: ")) {
System.out.println(ligne);
pass = ligne;
}
}
System.out.println(ligne);
System.out.println(id);
System.out.println(pass);
br1.close();
} catch (Exception ex) {
System.err.println("Error. "+ex.getMessage());
}
At the moment, I return to my String id the entire ligne, and same for pass – by the way, all the sysout are tests and are useless there.
If anybody knows how to send to id the line after the :and not the entire line, I probably searched bad, but google wasn't my friend.
Assuming there's only one : symbol in the string you can go with
id = ligne.substring(ligne.lastIndexOf(':') + 1);
Use StringUtils
StringUtils.substringAfter(id ,":"),
Why don't you try to do a split() on ligne?
If you use String[] splittedLigne = ligne.split(":");, you will have the following in splittedLigne:
splittedLigne[0] -> What is before the :
splittedLigne[1] -> What is after the :
This will give you what you need for every line. Also, this will work for you if you have more than one :.
i have a file similaire to this :
...
The hotspot server JVM has specific code-path optimizations
# which yield an approximate 10% gain over the client version.
export CATALINA_OPTS="$CATALINA_OPTS -server"
#############HDK1001#############
# Disable remote (distributed) garbage collection by Java clients
# and remove ability for applications to call explicit GC collection
export CATALINA_OPTS="$CATALINA_OPTS -XX:+DisableExplicitGC"
# Check for application specific parameters at startup
if [ -r "$CATALINA_BASE/bin/appenv.sh" ]; then
. "$CATALINA_BASE/bin/appenv.sh"
fi
#############HDK7564#############
# Disable remote (distributed) garbage collection by Java clients
# and remove ability for applications to call explicit GC collection
export CATALINA_OPTS="$CATALINA_OPTS -XX:+DisableExplicitGC"
i want to begin the reading from the line where exists the word "HDK1001" and end it where the world "HDK7564"
i tryed with this code but i am unable to do the limitation
public static HashMap<String, String> getEnvVariables(String scriptFile,String config) {
HashMap<String, String> vars = new HashMap<String, String>();
try {
FileInputStream fstream = new FileInputStream(scriptFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
String var= "HDK1001";
while ((strLine = br.readLine()) != null ) {
if (strLine.startsWith("export") && !strLine.contains("$")) {
strLine = strLine.substring(7);
Scanner scanner = new Scanner(strLine);
scanner.useDelimiter("=");
if (scanner.hasNext()) {
String name = scanner.next();
String value = scanner.next();
System.out.println(name+"="+value);
vars.put(name, value);
}
}
Help me please
try this code.
public static HashMap<String, String> getEnvVariables(String scriptFile,
String config) {
HashMap<String, String> vars = new HashMap<String, String>();
BufferedReader br = null;
try {
FileInputStream fstream = new FileInputStream(scriptFile);
br = new BufferedReader(new InputStreamReader(fstream));
String strLine = null;
String stopvar = "HDK7564";
String startvar = "HDK1001";
String keyword = "export";
do {
if (strLine != null && strLine.contains(startvar)) {
if (strLine.contains(stopvar)) {
return vars;
}
while (strLine != null && !strLine.contains(stopvar)) {
strLine = br.readLine();
if (strLine.startsWith(keyword)) {
strLine = strLine.substring(keyword.length())
.trim();
String[] split = strLine.split("=");
String name = split[0];
String value = split[1];
System.out.println(name + "=" + value);
vars.put(name, value);
}
}
}
} while ((strLine = br.readLine()) != null);
} catch (Exception e) {
e.printStackTrace();
}
return vars;
}
Your example code is quite far off, and I don't intend to rewrite all of your code, I will give you some pointers though. You are already doing:
if (strLine.startsWith("export") && !strLine.contains("$"))
This is your conditional that should be testing for the "HDK1001" string instead of whatever it's doing right now. I'm not sure why you are checking for the word "export" when it seems like it doesn't matter for your program.
There isn't a way to just magically start and end at specific words in the file, you MUST start at the beginning and go line by line checking all of them until you find your desired first and last line. Once you find that first line, you can continue reading until you reach your desired end line and then bail out.
this is pseudo code that follows the kind of logic you would want to be able to accomplish this task.
flag = false
inside a loop
{
read in a line
if( line != #############HDK1001############# && flag == false){ //check to see if you found your starting place
nothing useful here. lets go around the loop and try again
else // if i found it, set a flag to true
flag = true;
if( flag == true) // am i after my starting place but before my end place?
{
if( line == #############HDK1001#############)
do nothing and go back through the loop, this line is not useful to us
else if( line == #############HDK7564#############) //did i find my end place?
flag = false // yes i did, so lets not be able to assign stuff any more
else // im not at the start, im not at the end. I must be inbetwee. lets read the data and assign it.
read in the lines and assign it to variables that you want
}