Java - Using a config file
Java - Using a config file.
Rather than setting your variables all over the place in your code, you can create
static variables in a config file, set a file reader object, and have all static variables
stored in one location. May not be a huge deal with a single class file application, but when
you get into multiple classes, and/or extremely large classes when a variables data needs to
be changed you will only need to change it in the config file.
Lets get started:
Create a new javaProject and Class. (See my tutorial Creating a New Java Project in Eclipse) if
you are not sure how this is done.
1. First thing we will need to do is create a config file.
A. Right click on Project and select New --_ File. In the new File Dialog expand
project and click on the root folder. This is where we will want to save the config
file. Name your config file anything you like and Finish.
2.Next, lets get back to the .java file and import the io.file reader and util.properties.
import java.io.FileReader;
import java.util.Properties;
3. Add some data to the config file in the following format:
youTubeUrl=http:\\www.youtube.com
username=johndoe
password=pass123
NOTE - Must be in this exact format... fieldname=data (Case Sensitive)
4. Back to the .java file, I am going to wrap the the File Reader Object in a try/catch
which I will explain in another tutorial. For now lets just concentrate on the File Reader
object.
try(FileReader reader = new FileReader("config")) {
Properties properties = new Properties();
properties.load(reader);
}catch (Exception e) {;
e.printStackTrace();
}
5. Now we can start calling on the config file, and print out to the console for verification.
Setup some Strings using the get properties method(Which points to the config file.)
String youTubeUrl = properties.getProperty("youTubeUrl");
String userName = properties.getProperty("userName");
String password = properties.getProperty("password");
Now we will print out to the eclipse console to verify.
System.out.println(youTubeUrl);
System.out.println(userName);
System.out.println(password);
Note these are the field names in our config file.
RUN the application and verify all data has been output to the console with out any
errors. If this was an extremely larg application and you needed to change a fields data
its much quicker to change in one place in rather than every place in your code that
calls for it. As an example lets duplicate the 3 lines above and then make the change.
That's the quick rundown on using a config file for your Java project.
As always I hope this helped, Happy coding from TechMeNow2015.
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Java - Using a config file», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.