I am currently working on a small project to improve my programming skills, so not every “feature” might seem practical. Part of the application is a way to write notes and save them to a JList. While this notes-object is created, the content of the note (title and text) is saved to a .properties file. I picked the property-object because I needed some kind of key to allocate the content (text and title) to.
The Part for saving notes and creating the .properties file is working fine. But after closing and opening the application I want to populate the JList with the data in the .properties file. My problem now is that I want that the notes load in the same order as they were created in the first place. So if I create note a,b,c and close the application, I want that they load in this same order and I have a,b,c in my list again.
So I thought I’ll put the index of each file into the filename. This way the order in the notes directory on my hard disk is the same as in my JList. But this only works fine until you start deleting notes which messes up the order on the hard disk because of the id.
Can anyone give me a tip on how to solve this problem? I need a way to load the files in the same order they were created.
Here is the Code for adding notes:
private class AddNoteAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// Initialize variables
Properties data = new Properties();
FileOutputStream oStream = null;
// Create instance of note with the given text
String text = fldText.getText();
String title = fldTitle.getText();
Note note = new Note(text, title);
// Create new file in notes directory to save properties data
File file = new File(Config.NOTES_DIR, note.getId() + title + ".properties");
// Save data from userinput to properties file (date and id are being set when a new note object is created)
data.setProperty("title", title);
data.setProperty("text", text);
data.setProperty("created", note.getDate());
data.setProperty("id", String.valueOf(note.getId()));
// Write data from properties to file on the drive
try {
oStream = new FileOutputStream(file);
data.store(oStream, Config.APP_NAME + " Notes Data");
} catch (IOException e1) {
e1.printStackTrace();
}finally {
if(!(oStream == null)){
try {
oStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
// Add note to model
noteListModel.addNote(note);
// Clear Textfields after adding Note
fldText.setText("");
fldTitle.requestFocusInWindow();
fldTitle.setText("");
}
}
Here is the code for loading the notes:
public class LoadNotes {
// Initialize Variables
private NoteListModel noteModel;
private File folder = new File(Config.NOTES_DIR);
private File[] files = folder.listFiles();
private Properties data = new Properties();
private FileInputStream iStream = null;
// Load ListModel when creating instance of this class
public LoadNotes(NoteListModel noteModel){
this.noteModel = noteModel;
}
// Load text-files data from notes directory into properties and create new note
public void load(){
for (File file : files){
if(file.isFile()){
try {
iStream = new FileInputStream(file);
data.load(iStream);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(!(iStream == null)){
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Read data from file to property
String title = data.getProperty("title");
String text = data.getProperty("text");
int id = Integer.parseInt((data.getProperty("id")));
// Create new note instance and save to model
Note note = new Note(text,title);
noteModel.addNote(note);
}
}
}
Related
I have a camera that I am grabbing values pixel-wise and I'd like to write them to a text file. The newest updates for Android 12 requires me to use storage access framework, but the problem is that it isn't dynamic and I need to keep choosing files directory. So, this approach it succesfully creates my files but when writting to it, I need to specifically select the dir it'll save to, which isn't feasible to me, as the temperature is grabbed for every frame and every pixel. My temperature values are in the temperature1 array, I'd like to know how can I add consistently add the values of temperature1 to a text file?
EDIT: I tried doing the following to create a text file using getExternalFilesDir():
private String filename = "myFile.txt";
private String filepath = "myFileDir";
public void onClick(final View view) {
switch (view.getId()){
case R.id.camera_button:
synchronized (mSync) {
if (isTemp) {
tempTureing();
fileContent = "Hello, I am a saved text inside a text file!";
if(!fileContent.equals("")){
File myExternalFile = new File(getExternalFilesDir(filepath), filename);
FileOutputStream fos = null;
try{
fos = new FileOutputStream(myExternalFile);
fos.write(fileContent.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
Log.e("TAG", "file: "+myExternalFile);
}
isTemp = false;
//Log.e(TAG, "isCorrect:" + mUVCCamera.isCorrect());
} else {
stopTemp();
isTemp = true;
}
}
break;
I can actually go all the way to the path /storage/emulated/0/Android/data/com.MyApp.app/files/myFileDir/ but strangely there is no such file as myFile.txt inside this directory, how come??
Working Solution:
public void WriteToFile(String fileName, String content){
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File newDir = new File(path + "/" + fileName);
try{
if (!newDir.exists()) {
newDir.mkdir();
}
FileOutputStream writer = new FileOutputStream(new File(path, filename));
writer.write(content.getBytes());
writer.close();
Log.e("TAG", "Wrote to file: "+fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
I have a JavaFX project with 2 modules..
[Project structure][1]
public class SkiResortModel {
private static final String FILE_NAME_RESORTS = "/SKI_RESORTS.csv";
//Code for reading file is:
private BufferedReader getReader() {
InputStream inputStreamResorts = getClass().getResourceAsStream(SkiResortModel.FILE_NAME_RESORTS);
assert inputStreamResorts != null;
InputStreamReader readerResorts = new InputStreamReader(inputStreamResorts, StandardCharsets.UTF_8);
return new BufferedReader(readerResorts);
}
private List<SkiResortModel> readFromFile() {
try (BufferedReader reader = getReader()) {
return reader.lines()
.skip(1)
.map(line -> new SkiResortModel(line.split(DELIMITER, 0)))
.collect(Collectors.toList());
} catch (IOException e) {
throw new IllegalStateException("failed");
}
}
//Code for writing file is:
private BufferedWriter getWriter(String filename) {
try {
String file = Objects.requireNonNull(getClass().getResource(filename)).getFile();
return new BufferedWriter(new FileWriter(file, StandardCharsets.UTF_8));
} catch (IOException e) {
throw new IllegalStateException("wrong file " + filename);
}
}
public void save() {
try (BufferedWriter writer = getWriter(FILE_NAME_RESORTS)) {
writer.write(
"ENTITY_ID;NAME;REGION;COMMUNES_IN_RESORT;MASL_MIN;MASL_MAX;SKI_RUNS_KM;DRAG_LIFTS;CHAIR_LIFTS;CABLE_CARS;OPEN_LIFTS;SNOW_DEPTH_CM;VISITORS_TODAY;CAR_FREE;FUNPARK_AVAILABLE;IMAGE_URL");
writer.newLine();
int id = 100;
for (SkiResortModel s : allSkiResorts) {
writer.write(s.infoAsLine(";", id));
writer.newLine();
id++;
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
We have created a small application which displays the data in a table and allows for some modification. The data should then be written back into the original csv file.
The data is stored in the resources folder (screenshot). When the save function is called the data should then be written back into the original csv-file. However Intellij creates a new csv file under skiresorts-model/target.
I tried to indicate the path by copying the path from the context menue (Right click on file => Copy path / reference. I tried all the options to copy the path but then the program is unable to find the file. Strange is also that after I used copy path/reference
the program is unable to run even with the original path. The only thing that helps then is to check out another branch and return to the branch. Is this a bug in Intellij?
The save function is called from another class after the modifications have been done.
Any help is greatly appreciated.
[1]: https://i.stack.imgur.com/NwtB2.png
I'm creating a little java app and I'm trying to load the yml files based on config.yml lang set (en/it) but I can't find a way to load them, only the last one in an array is loaded which is "it" for me.
I know that my method is probably the worst solution for a language file, I'm open to every method that will help me with the problem. But I prefer an external lang_en/it file instead of internal ones (Or is it better internal?)
After I set the language, the app will self-update every text in every class.
static final Properties props = new Properties();
static WelcomeMessage main = new WelcomeMessage();
static File file = null;
static File folder = null;
static boolean os = main.os.startsWith("Windows");
public static void create() {
String[] lang = {"en", "it"};
for (String s : lang) {
file = new File(WelcomeMessage.user + "/AppData/Roaming/MyApp/lang_" + s + ".yml");
folder = new File(file.getParent());
SetLanguages(s);
}
if (!file.exists()) {
try {
if (os) {
folder.mkdir();
file.createNewFile();
} else {
file = new File(main.user + "/Library/Application Support/MyApp/config.yml");
folder.mkdir();
file.createNewFile();
}
} catch (Exception e) {
System.out.println(e + " " + file);
}
}
}
public static void SetLanguages(String lang) {
if (lang.equals("en")) {
store("Settings.Save", "Save");
store("Settings.ConfigPath", "Config Path");
store("Settings.Language", "Language");
store("Settings.Title", "Settings");
} else if (lang.equals("it")) {
store("Settings.Save", "Salva");
store("Settings.ConfigPath", "Percorso config");
store("Settings.Language", "Lingua");
store("Settings.Title", "Impostazioni");
}
}
public static String get(String value) {
String key = null;
try {
FileInputStream in = new FileInputStream(file);
props.load(in);
key = props.getProperty(value);
in.close();
} catch (Exception fnf) {
System.out.println(fnf);
}
return key;
}
public static void store(String value, String key) {
try {
FileOutputStream out = new FileOutputStream(file);
props.setProperty(value, key);
props.store(out, null);
out.close();
} catch (Exception fnf) {
System.out.println(fnf);
}
}
This is how I get a text from yml:
path.setText(Language.get("Settings.ConfigPath"));
language.setText(Language.get("Settings.Language"));
f.setTitle(Language.get("Settings.Title"));
save.setText(Language.get("Settings.Save"));
And this my Language.get(key)
public static String get(String value) {
String key = null;
try {
FileInputStream in = new FileInputStream(file);
props.load(in);
key = props.getProperty(value);
in.close();
} catch (Exception fnf) {
System.out.println(fnf);
}
return key;
}
I suggest the following changes:
Create a Settings class to hold the properties save, configPath, language and title. Even better if this class uses an immutable builder pattern, because once set, the properties will never change.
Create a SettingsFactory class with method getSettings(language). This class shall also have a field Map<String, Settings>. In the constructor (or a static block), first check if a file exists on the disk, and if yes, load it into the map. If not, populate the map, one entry for each language, and persist to the disk.
getSettings would simply return the value from the map corresponding to the given language.
The format of the file written to the disk is a different matter. You say YAML, but I'm not seeing any YAML specific code in your snippet. If you don't know how to write a map to YAML, open a different question.
I am trying to make an application that will create Google Authenticator secret keys, as well as authenticate the OTP. I am writing all of my passwords to individual files titled with the name that goes along with them.
First and foremost, I am using this library.
https://github.com/aerogear/aerogear-otp-java
This is my code:
public void createUserFile(String name) throws IOException
{
File file = new File("users\\" + name + ".txt");
file.createNewFile();
}
public void generateUserKey(String name)
{
try
{
File file = new File("users\\" + name + ".txt");
FileWriter fw = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fw);
String s = Base32.random();
out.write(s);
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
If I change the value of s to something like "Hello" I am fine. However, it will not write that random string. That is what I need help with. I have tinkered and searched hours for answers, and I have found nothing.
I don't believe you need createUserFile, and it isn't clear you necessarily know where the "users/" folder (a relative path) is. I suggest you use System.getProperty(String) to get user.home (the User home directory).
I would also suggest you use a try-with-resources Statement and a PrintStream. Something like
public void generateUserKey(String name) {
File file = new File(System.getProperty("user.home"), //
String.format("%s.txt", name));
try (PrintStream ps = new PrintStream(file)) {
ps.print(Base32.random());
} catch (IOException e) {
e.printStackTrace();
}
}
having a lil issue, i have create a properties file :
config.properties located in ../resource/config.properties
this is the file currently :
destinationPDF=D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/
destination="D:/Documents/NetBeansProjects/printing~subversion/fileupload/Uploaded/
fileList =D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/Directory Files/directoryFiles.txt
have i done the properties file ok ?
also i want to access this file and load the variables into a class
i have tried
public void loadProp() {
try {
prop.load(new FileInputStream("../resources/config.properties"));
System.out.println(prop.getProperty("destinationPDF"));
System.out.println(prop.getProperty("destination"));
System.out.println(prop.getProperty("fileList"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
but now the class will not compile becuase it can not find variable destination for example, so how do i load the variables from the file, and do i still need to declear the variable in the class ?
sorry if these are silly questions, first time using properties !
i do not get this error if i put in the variables normally like
private String destinationPDF = "D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/"; //USE ON TORNADO//"D:/My Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/";//USE ON PREDATOR
EDIT:
have now
private Properties configProp = new Properties();
public void loadProps() {
InputStream in = this.getClass().getClassLoader().getResourceAsStream("../resources/config.properties");
try {
configProp.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT 2:
public void loadProp() {
InputStream in = this.getClass().getClassLoader().getResourceAsStream("../resources/config.properties");
try {
prop.load(in);
System.out.println(prop.getProperty("destinationPDF"));
System.out.println(prop.getProperty("destination"));
System.out.println(prop.getProperty("fileList"));
} catch (IOException e) {
e.printStackTrace();
}
}
Properties prop = new Properties();
private String destinationPDF = prop.getProperty("destinationPDF");
public String destination = prop.getProperty("destination");
it is working, no erors etc but destination and destinationPDF are passing null values
You seem to misunderstand what properties files are. They're just data. They don't contain Java code, and aren't used to declare variables. To get the value associated to the key destinationPDF in the properties file, you need to call
String destinationPDF = prop.getProperty("destinationPDF");
after having initialized the prop variable and loaded the file using prop.load(new FileInputStream(...)). And then you'll have a variable initialized with the value of the key.
Side note: please respect the Java naming conventions: variables start with a lower-case letter.
Problem is here:
// destination = "D:/Documents/NetBeansProjects/printing~subversion/fileupload/Uploaded/"; // main location for uploads (CHANGE THIS WHEN USING PREDATOR)
File theFile = new File(destination + "/" + username);
theFile.mkdirs();// will create a sub folder for each user (currently does not work, below hopefully is a solution) (DOES NOW WORK)
System.out.println("Completed Creation of folder");
NewDestination = destination + username + "/";
You have commented the destination variable and you are using here:
NewDestination = destination + username + "/";
I wonder whats the issue...I tested your code and it works fine...are you getting compilation error or runtime error?
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Test1 {
/**
* #param args
*/
public static void main(String[] args) {
new Test1().loadProp();
}
Properties prop = new Properties();
public void loadProp() {
try {
prop.load(new FileInputStream("c:/Test/Computer.txt"));
System.out.println(prop.getProperty("destinationPDF"));
System.out.println(prop.getProperty("destination"));
System.out.println(prop.getProperty("fileList"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Output:
D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/
D:/Documents/NetBeansProjects/printing~subversion/fileupload/Uploaded/
D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/Directory Files/directoryFiles.txt