How can I read a path from an .ini file - java

I would like to import a file path in Java. Since the path can change, I want it to be outside of the code and so it is changeable. I have read that that can solve with an INI file. Well, I've tried it. I have the following Java code:
import java.util.*;
import java.io.*;
class readIni {
public static void main(String args[]) {
readIni ini = new readIni();
ini.doit();
}
public void doit() {
try{
Properties p = new Properties();
p.load(new FileInputStream("user.ini"));
p.list(System.out);
}
catch (Exception e) {
System.out.println(e);
}
}
}
My Ini-file:
file = H:/
Now, the console shows exactly the Ini-file and not the contents of the directory....What is wrong?

If you want to just save a file path, consider using the following code:
File file = new File("H:\whatever.txt");
// Write to the file
FileWriter fw = new FileWriter(file);
fw.write("your path goes here");
fw.close();
// Read from the file
BufferedReader br = new BufferedReader(new FileReader(file));
String path = br.readLine();
br.close();

Related

File in the asked folder

I'm trying to make a small program that allows to create a 'txt' file. My teacher taught me to use BufferedReader and PrintWriter but I don't know how to allow the user to choose the path (you know, like when you save something on a software).
Thanx for your answer.
(Sorry for my english, not my native language)
You can input it with a Scanner, and then append the file name to it using Path#get:
System.out.println("Please enter the target directory: ");
Scanner in = new Scanner(System.in);
String dir = in.next();
String filePath = Paths.get(dir, "myfile.txt").toString();
// Go on and create the file as you would normally do
I assume you want to use BufferedReader and it is console app.
public class CreateFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in));) {
System.out.println("Enter the path");
String path = br.readLine();
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
System.out.println("File is created!");
}
}
}
Output
Enter the path
./file/test.txt
File is created!
with interface, for simplest way to get user input
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JOptionPane;
public class CreateFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String path = JOptionPane.showInputDialog("Enter the path");
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
System.out.println("File is created!");
}
}
}
here is Java Swing – JOptionPane showInputDialog example

How to read a yaml file to a string with the correct indentation

I need to read a yaml file and get the content of it to a String.
As the yaml format need the right indentation, I have to get the exact content as in the file. The normal way of reading a file in java doesn't work for me.
So if anyone can tell me how to read the content of a yaml file into a String variable.
Again the question is,
How to read the content of a yaml file with the indentation and spaces and get the content of the file into a String variable in java? In other words, I need the content of the yaml file as it is to a String variable.
Anyway, you have figured it out, but here is the code for proper indentation.
package test;
import java.io.BufferedReader;
import java.io.FileReader;
public class test {
private static String FILENAME = "input.txt";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
StringBuffer stringBuffer = new StringBuffer();
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
stringBuffer.append(sCurrentLine);
stringBuffer.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(stringBuffer);
}
}

how to append the data in java file?

i just need your help. I'm learning java(OOP) and now days we are working on filing. But i got stuck on how to append data in the file. I have written the code and and here's the part of it which is showing the error. Can someone please help me what's wrong with it and why it is not working?
package appending;
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class open {
Formatter output;
public void openFile() throws FileNotFoundException {
output = new Formatter("E:/thisFile.txt");
}
public void addData() {
Scanner input = new Scanner(System.in);
data d = new data();
System.out.println("Enter the data");
d.setData(input.next(),input.nextInt());
output.format("%s","Name and CMS:\t"+d.getData());
FileWriter fileWritter = new FileWriter(File.getPath(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(d.getData());
bufferWritter.close();
}
public void close() {
output.close();
}
}
Can try,
public class FileAppend {
public static void main(String[] args) {
PrintWriter out = null;
try{
out = new PrintWriter(new BufferedWriter(new FileWriter("/home/rakesh/myfile.txt", true)));
out.println("appended text");
} catch(Exception e){
e.printStackTrace();
} finally{
out.close();
}
}
}
Creating a text file (note that this will overwrite the file if it already exists):
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Creating a binary file (will also overwrite the file):
byte dataToWrite[] = //...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(dataToWrite);
out.close();
Answer gotten from: How do I create a file and write to it in Java?
If you want to use FileWriter. Try following code:
//FileWriter fw = new FileWriter(new File("path/to/test.txt"), true);
FileWriter fw = new FileWriter("path/to/test.txt", true);
fw.write("This is a sentence");
fw.close();
EDIT You should follow the conventions and capitalize your classes.

Taking data from one text file and moving it to a new text file

I have a file that has data inside of it. In my main method I read in the file and closed the file. I call another method that created a new file inside of the same folder of the original file. So now I have two files, the original file and the file that is being made from the method that I call. I need another method that takes the data from the original file and writes it to the new file that is created. How do I do that?
import java.io.*;
import java.util.Scanner;
import java.util.*;
import java.lang.*;
public class alice {
public static void main(String[] args) throws FileNotFoundException {
String filename = ("/Users/DAndre/Desktop/Alice/wonder1.txt");
File textFile = new File(filename);
Scanner in = new Scanner(textFile);
in.close();
newFile();
}
public static void newFile() {
final Formatter x;
try {
x = new Formatter("/Users/DAndre/Desktop/Alice/new1.text");
System.out.println("you created a new file");
} catch (Exception e) {
System.out.println("Did not work");
}
}
private static void newData() {
}
}
If your requirement is to copy your original files content to new file. Then this may be a solution.
Solution:
First, read to your original file using BufferedReader and pass your content to another method which creates new file using PrintWriter. and add your content to your new file.
Example:
public class CopyFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = ("C:\\Users\\yubaraj\\Desktop\\wonder1.txt");
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "C:\\Users\\yubaraj\\Desktop\\new1.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Read created at runtime file with java

I create and write a file with a java method, then I want to read this file at runtime with another java method.But it throws java.io.FileNotFoundException error.
How could I fix this error?
Writer output=null;
File file = new File("train.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(trainVal[0] + "\n");
-------------------
and read code
FileInputStream fstreamItem = new FileInputStream("train.tx");
DataInputStream inItem = new DataInputStream(fstreamItem);
BufferedReader brItem = new BufferedReader(new InputStreamReader(inItem));
String phraseItem;
ArrayList<Double> qiF = new ArrayList<Double>();
while ((phrase = br.readLine()) != null) {
//doing somethinh here
}
Use the correct file name. This includes the path to the file. Also make sure that no one deleted the file between those two functions or renamed it.
The following is one of the best and convenient methods to read a file. Go through it instead of using traditional methods.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
final public class Main
{
public static void main(String... args)
{
File file = new File("G:/myFile.txt"); //Mention your absolute file path here.
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner=null;
try
{
scanner = new Scanner(file);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
String lineSeparator = System.getProperty("line.separator");
try
{
while(scanner.hasNextLine())
{
fileContents.append(scanner.nextLine()).append(lineSeparator);
}
}
finally
{
scanner.close();
}
System.out.println(fileContents); //Displays the file contents directly no need to loop through.
}
}
You have made a mistake in giving a proper file extension in your code.
FileInputStream fstreamItem = new FileInputStream("train.tx");
Should have been
FileInputStream fstreamItem = new FileInputStream("train.txt");

Categories