ini4j Read File Error - java

I am trying to use ini4j. But I am not able to read the file. The code:
ini = new Wini(new InputStreamReader(new FileInputStream("./setup.ini"), "UTF-8"));
But it is giving me the errors:
Unhandled exception type IOException
Unhandled exception type InvalidFileFormatException
Unhandled exception type UnsupportedEncodingException
Unhandled exception type FileNotFoundException
I already tried "C:\setup.ini" and "setup.ini" and "C:/setup.ini"
I also tried:
ini = new Wini(new InputStreamReader(new FileInputStream(New File("./setup.ini")), "UTF-8"));
The Variable ini is properly declared:
Wini ini;
Any Ideas?

Simple Windows .ini file
[main]
window-color = 00ffff
splash = true
[others]
version = 0.1
developer = Jim
Reading from .ini file
import java.io.File;
import java.io.IOException;
import org.ini4j.InvalidFileFormatException;
import org.ini4j.Wini;
public class Main {
public static void main(String args[]){
try{
Wini ini;
/* Load the ini file. */
ini = new Wini(new File("config/settings.ini"));
/* Extract the window color value.*/
int windowColor = ini.get("main", "window-color", int.class);
/* Extract the splash screen status. */
boolean splashScreen = ini.get("main", "splash", boolean.class);
/* Show to user the output. */
System.out.println("Your default window color is: " + windowColor);
if(splashScreen){
System.out.println("You have your splash screen activated.");
}else{
System.out.println("You have your splash disabled.");
}
} catch (InvalidFileFormatException e) {
System.out.println("Invalid file format.");
} catch (IOException e) {
System.out.println("Problem reading file.");
}
}
}
Writing to .ini file
import java.io.File;
import java.io.IOException;
import org.ini4j.InvalidFileFormatException;
import org.ini4j.Wini;
public class Main {
public static void main(String args[]){
Wini ini;
try {
ini = new Wini(new File("config/settings.ini"));
ini.put("main", "window-color", 000000);
ini.put("main", "splash", false);
ini.store();
} catch (InvalidFileFormatException e) {
System.out.println("Invalid file format.");
} catch (IOException e) {
System.out.println("Problem reading file.");
}
}

Related

How to use contents of a string as object name of a class constructor in Java and can I use object of a class more than one times?

I am making a program which will create files and delete files etc. but the program can only create one file and after doing that it gets terminated, so I want to use String as name of create_file class object name so I can increment the numbers(String used as name of the object) so my question is, how can I use String as object name of a class constructor?
below is the source code of the program-
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Create_File {
public static void main(String[] args) throws IOException {
try {
Selecter.select();
}
catch(Exception e) {
e.printStackTrace();
}
}
static void create() throws IOException {
String name;
System.out.println("Enter a name for your file");
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));){
name = reader.readLine();
//this block is used as try with resource statement used to overcome scanner resource leak
}
try{
//file is created with the name that user gives
File obj = new File("D:\\txtfiles\\"+name+".txt");
if(obj.createNewFile()) {
System.out.println("file successfully created with the name "+obj.getName());
}
else{
System.out.println("The file already exists");
}
}
catch(IOException e){
//here exception during file creation is caught
System.out.println("An error occurred.");
e.printStackTrace();
}
// info(name);
name = null;
// Selecter.select();
}
static void info(String name) throws IOException {
File obj = new File("D:\\txtfiles\\"+name+".txt");
String data = null;
Scanner scan = new Scanner(obj);
if(obj.exists()) {
//file properties are printed out for both newly created file and the existing file
System.out.println("File properties");
System.out.println("Name of the file = "+obj.getName());
System.out.println("Path of file = "+obj.getAbsolutePath());
System.out.println("Size of file in Kb= "+obj.length()/1024); // obj.lengeth is divided by 1024 to get the file size in Kb
System.out.println("Readable = "+obj.canRead());
System.out.println("Writable = "+obj.canWrite());
}
else {System.out.println("the file does not exist");
//this block is used as try with resource statement used to overcome scanner resource leak
while(scan.hasNextLine()) {
data = scan.nextLine();
System.out.println(data);
}
}
// Selecter.select();
}
static void delete(String name) throws IOException {
try{
File obj = new File("D:\\txtfiles\\"+name+".txt");
obj.delete();
if(obj.exists()==false) {
System.out.println("file deleted successfully");
}
else {
System.out.println("file does not exist");
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
below is the source code of Selecter class-
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class Selecter {
static void select() throws IOException {
String num=null;
Create_File create =new Create_File();
System.out.println("Select Action");
System.out.println("1. Create new text file");
System.out.println("2. Delete an existing file");
System.out.println("3. Find info of a file");
System.out.println("4. Print the contents of a file");
System.out.println("5. EXIT");
System.out.println("Your choice = ");
try
(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));){
int choice = Integer.parseInt(num= reader.readLine());
if(choice==1) {
create.create();
}
else if(choice == 2){
System.out.println("enter file name to delete");
String name=reader.readLine();
create.delete(name);
}
else if(choice == 3) {
System.out.println("enter file name to find its info");
String name= reader.readLine();
create.info(name);
}
else if(choice ==4) {
Buffer contents = new Buffer();
Buffer.main(null);
}
else if(choice == 5) {
System.exit(0);
}
}
// select();
}
}
or is there an alternative solution for this problem I want the program to keep running till the user wants to exit.

Printing a string to a file in all uppercase, lowercase and reverse java

I need to input a line of text into the code and have it print that text to the file in all upper came, all lower case, and reverse. I know how to do this with string, but cannot figure out how to get it to print to the file this way. I do not need help with getting the text to print in the output but getting it to print all these ways to the actual PrintToFile.txt without actually inputting it all those different ways.
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class PrintToFile { //open class
private static Formatter output;
public static void main (String args[]) throws IOException { //open main
openFile();
addRecords();
closeFile();
BufferedReader printFile = new BufferedReader(new FileReader("YoastReginaITM251Project9.txt"));
for (String line; (line = printFile.readLine()) != null;) { //open for
System.out.println("Text: " + line);
System.out.println("Text in Upper Case: " + line.toUpperCase());
System.out.println("Text in Lower Case: " + line.toLowerCase());
System.out.println("Text in Reverse Case: " + line);
} //close for
} //close main
public static void openFile() { //open openFile
try { //open try
output = new Formatter("PrintToFile.txt"); //open file
} //close try
catch (SecurityException securityException) { //open catch
System.err.println("Write permission denied. Terminating.");
System.exit(1);
} //close catch
catch (FileNotFoundException fileNotFoundException) { //open catch
System.err.println("Error opening file. Terminating.");
System.exit(1);
} //close catch
} //close openFile
public static void addRecords() { //open addRecords
try { //open try
output.format("%s", input.nextLine());
} //close try
catch (FormatterClosedException formatterClosedException) { //open catch
System.err.println("Error writing to file. Terminating.");
} //close catch
catch (NoSuchElementException elementExpcetion) { //open catch
System.err.println("Invalid input. Please try again.");
input.nextLine();
} //close catch
} //close AddRecords
public static void closeFile() { //open closeFile
if (output != null)
output.close();
} //close closeFile
} //close class
String input = "MagicString";
String upperCase = input.toUpperCase();
String lowerCase = input.toLowerCase();
StringBuilder sb = new StringBuilder();
sb.append(input);
String reversedString = sb.reverse().toString();
You can use the StringBuilder class (https://docs.oracle.com/javase/tutorial/java/data/buffers.html) to create new strings as you like, then print those to file.
The simple way is:
Read from a file into a string.
Apply toUpperCase() and store it into another string.
Apply toLowerCase() and store it into another string.
Apply reverse()[own created method] and store it into another string.
Then write all these strings into the destination file.
Here is the code by which you can perform the required operation.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class FileRW {
public static void main(String[] args) throws FileNotFoundException, IOException {
String filename="filename.txt";
String upper,lower,reverse,line;
upper=null;
lower=null;
reverse=null;
line=null;
FileReader fileReader=new FileReader(filename);
BufferedReader bufferedReader=new BufferedReader(fileReader);
while((line=bufferedReader.readLine())!=null)
{
upper=line.toUpperCase();
lower=line.toLowerCase();
reverse=reverse(line);
writeToFile(upper,lower,reverse);
}
}
static String reverse(String test)
{ String returnString="";
int len=test.length();
for(int i=len-1;i>=0;i--)
{
returnString+=test.charAt(i);
}
return returnString;
}
static void writeToFile(String line1,String line2,String line3) throws IOException
{
String filename="content.txt";
File file =new File(filename);
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(line1);
bufferWritter.write(line3);
bufferWritter.write(line2);
bufferWritter.close();
System.out.println("Done");
}
}
Maybe you could use the Scanner and FileWriter classes as well. You can try something like this if it works for your purposes:
import java.io.*;
import java.util.*;
public class Solution{
/*
* Print a string to the output file
*/
private void print(String s, FileWriter o) {
try {
o.write(s + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* Convert the strings to uppercase,
* lowercase and reverse.
*/
private void solver(Scanner sc, FileWriter o){
while(sc.hasNextLine()) {
String s = sc.nextLine();
print(s.toUpperCase(), o);
print(s.toLowerCase(), o);
print(new StringBuilder(s).reverse().toString(), o);
}
}
/*
* Main method
*/
public static void main(String args[]){
File inFile = new File("input.txt");
File outFile = new File("output.txt");
try{
Scanner sc = new Scanner(inFile);
FileWriter o = new FileWriter(outFile);
Solution s = new Solution();
s.solver(sc, o);
sc.close();
o.close();
} catch(Exception e){
System.out.println(e);
}
}
}

cannot create a txt file

import java.util.Scanner;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class Exercise4
{
String name = null;
public String nameInitials(String sentence)
{
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(new FileOutputStream("abc.txt."));
outputStream.println(sentence);
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
System.exit(0);
}
outputStream.close();
Scanner inputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("abc.txt."));
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
System.exit(0);
}
do
{
String word = inputStream.next();
char initial = word.charAt(0);
name = initial+"."+name;
} while (inputStream.hasNext());
return name;
}
public void main(String[]args)
{
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials);
}
}
Write a method called nameInitials that takes one String as argument, pertaining to somebody's full name and returns a String of the name's initials. Usage example,
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials); //should print B.A.W.R.
I try to store the full name to a txt file and read the file. But I don't know why I cannot create the abc.txt file in the folder.
This can fix your error, I tested it
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class Exercise4
{
static String name = null;
public static String nameInitials(String sentence) {
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(new FileOutputStream("C:\\temp\\abc.txt"));
outputStream.println(sentence);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
outputStream.close();
Scanner inputStream = null;
try {
inputStream = new Scanner(new FileInputStream("C:\\temp\\abc.txt"));
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
do {
String word = inputStream.next();
char initial = word.charAt(0);
name = initial + "." + name;
} while (inputStream.hasNext());
return name;
}
public static void main(String[] args) {
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials);
}
}
the path of file not should end of .txt. just .txt
Your code is perfect it is creating the file "abc.txt." at the project level If you want to create a file named abc.txt then you must change;
new FileOutputStream("abc.txt.") to new FileOutputStream("abc.txt")
and
new FileInputStream("abc.txt.") to new FileInputStream("abc.txt")
And if you want to create the file in a particular directory then provide the full path of that directory with the file name you want to create.
for ubuntu system;
new FileOutputStream("/home/java/abc.txt")
&
new FileInputStream("/home/java/abc.txt")
and for windows system;
new FileOutputStream("C:/java/abc.txt")
&
new FileInputStream("C:/java/abc.txt")

How to read file in ideone in java

I want to open, read, and edit file from my desktop. I am using Ideone online compiler. How do I read the file? I tried the following code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
class demo
{
public static void main(String[] args)
{
System.out.println("Hello World!");
File file = new File("C:/Users/psanghavi/Desktop/admin_confirmation_original.txt");
if (!file.exists())
{
System.out.println("does not exist.");
return;
}
if (!(file.isFile() && file.canRead()))
{
System.out.println(file.getName() + " cannot be read from.");
return;
}
try
{
FileInputStream fis = new FileInputStream(file);
char current;
while (fis.available() > 0)
{
current = (char) fis.read();
System.out.print(current);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
My desktop has file named: admin_confirmation_original.txt
Currently, No. About the limit, Idebone FAQ say about this:
Can I write or read files in my program? - No
Can I access the network from my program? - No
You can learn more about many Ideone restricted rule at FAQ.
Ideoone doesn't support reading local files.
This is not an answer to your question, but wrt to the comments
if you want to read files hosted, you could access them using URL class.
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Demo {
public static void main(String[] args) throws IOException {
try {
final URL url = new URL("http://www.google.co.in/robots.txt");
//URL url = new URL("http://74.125.236.52/robots.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String str;
while (in.readLine() != null) {
str = in.readLine();
System.out.println(str);
}
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
I have not tried it on file hosting sites.There are a lot of free file hostings available just google it.

Is there a way to make this Java program more interactive?

I have written the following very simple Java program to ask user enter a file name, then it will report the number of lines of this file to the standard output:
import java.io.*;
import java.util.*;
public class CountLine {
public static void main(String[] args)
{
// prompt the user to enter their file name
System.out.print("Please enter your file name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
fileName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the file name, " + fileName);
File file = new File("C:/Users/Will/Desktop/"+fileName);
Scanner scanner;
try {
scanner = new Scanner(file);
int count =0;
String currentLine;
while(scanner.hasNextLine())
{
currentLine=scanner.nextLine();
count++;
}
System.out.println("The number of lines in this file is "+count);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("There is no such file");
e.printStackTrace();
}
}
}
It is working.I would be really thankful if experts could help me
see if there is anything that can be improved in this code fragment,
If the file is not found, the exception is caught in the outermost catch statement and print out the stack trace. However, I think it is not very user-friendly, is there a way if the file does not exist, then the whole process restarts from beginning?
Thanks in advance.
Get some Structure in your code:
public static void main(String[] args)
{
string output;
string fname = readFileName();
if (fileValid(fname)) //Ensure FileExists
{
int lineCount = scaneFile(fname);
output = "some output text including line numbers"
}
else
{
output = "File Not Valid..."
}
//showOutput...
}
Obvious change is to make a method countLines(String filename) that contains most of the code currently in main(). Obviously main() will call countLines().
Prompting for a file could live in main() or another method.
To restart on error you need a loop like:
filename = // read filename from stdin;
while(keepGoing(filename)) { // null check or whatever to let you out of the loop
try {
int numLines = countLines(filename);
println("num lines in " + filename + "=" +numLines);
}
catch(Exception ex) { // or just specific excpetions
ex.printStackTrace();
}
}
Unless you want to make a GUI. I suggest you receive the path to the file as a command line parameter.
If file doesn't exist print a message and exit. That's all.
The command line will give the user the option to move up with the up-key, edit the name and run again.
This class is named LineCounter and is the "business logic"
package countlines;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
private int lineCount = 0;
public LineCounter(File file) throws IOException{
BufferedReader inFile = new BufferedReader(new FileReader(file));
while(inFile.readLine() != null) {
lineCount++;
}
inFile.close();
}
public int getLineCount() {
return lineCount;
}
}
This class is the "presentation logic"
package countlines;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main (String[] args){
if (args.length != 1){
System.out.println("Usage: java countlines/Main filePath");
System.exit(1);
}
File f = new File(args[0]);
if (!f.exists()){
System.out.println("File "+f.getAbsolutePath()+" doesn't exist");
System.exit(2);
}
if (f.isDirectory()){
System.out.println(f.getAbsolutePath()+" is a directory");
System.exit(2);
}
LineCounter c;
try {
c = new LineCounter(f);
System.out.println(c.getLineCount());
} catch (IOException e) {
System.out.println("Error reading file " + f.getAbsolutePath());
}
}
}

Categories

Resources