I am new to Java , I am currently analyzing a file compare tool with java that compare two files from this link:
http://www.java2s.com/Code/Java/File-Input-Output/Difftextfiledifferenceutility.htm
But no where in the file, the file path is mentioned. Where should I insert the file path? I searched google and checked Java Filestram and buffer input output stream. But did not found any useful information.
I also searched stackoverflow but it seems no such question exists.
Usually, the file path should be updated in main file, right?
But it seems that is missing in main file.
public static void main(String argstrings[])
{
if ( argstrings.length != 2 ) {
System.err.println("Usage: diff oldfile newfile" );
System.exit(1);
}
Diff d = new Diff();
d.doDiff(argstrings[0], argstrings[1]);
return;
}
Your program takes the file names as the parameter. So while giving the command line input you can give the full file paths. Something like this:
java yourClassName volume1:\dir1\filename1 volume2:\dir2\filename2
You can certainly do the way juned told you but if you want to the program to be more user friendly try to manipulate the main method like this
public static void main(String[] args) throws ParseException {
try{
Scanner in = new Scanner(System.in);
System.out.println("Enter the path of old file");
String oldFile = in.nextLine();
System.out.println("Enter the path of new file");
String newFile = in.nextLine();
Diff d = new Diff();
if(!oldFile.equals("") && !newFile.equals("")) {
d.doDiff(oldFile, newFile);
}
}
catch (Exception e){
e.printStackTrace();
}
}
Related
I'm working on a program that reads from a file with a custom extension I made. The idea is that an error report is created every time a file is read. The error report must be in whatever folder the source file was called from. The error file is a copy of the source file, but it has a line number at the beginning of each line and indicates at the end of the line if an error occurred at that line.
(I'm not trying to set up the numbering on this question, this question is just about creating the copy)
So for example, when I call my program from the command prompt:
C:\MyLocation>java =jar myJavaProgram.jar myFileToRead.CustomExtension
Asides from reading the file, it should also create a copy at the same location called myFileToRead-ErrorReport.txt
Additionally: If the source file has no extension, I have to assume that it's still the correct extension, so there won't always be a '.myCustomExtension' segment to replace into .txt
The problem is that I don't know how to grab the file name, because it's coming from the args list of the main method. I am using the following to read the file
public static void main(String[] args) throws FileNotFoundException {
try{
File inputFile = new File(args[0]);
Scanner sc = new Scanner(inputFile);
while(sc.hasNext()){
System.out.println(sc.nextLine());
}
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
System.out.println("File not found.");
}
}
So how can I get that file name to make something like
File errorReport = new File("./" + inputFileName + ".txt"); ?
First the code. The explanations appear after the code.
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("ERROR: Missing filename argument.");
}
else {
String filename = args[0];
if (filename.length() == 0) {
System.out.println("ERROR: Empty filename argument.");
}
else {
if (!filename.endsWith(".CustomExtension")) {
filename += ".CustomExtension";
}
String name = filename.substring(0, filename.indexOf(".CustomExtension"));
name += "-ErrorReport.txt";
File inputFile = new File(filename);
File directory = inputFile.getParentFile();
File errorReport = new File(directory, name);
System.out.println(errorReport.getAbsolutePath());
}
}
}
I make it a habit of checking the parameters. Hence I first check that the file name was supplied. If it was, then I check that it is not an empty string. Note that I have omitted some checks, for example checking whether the named file exists and is readable.
You wrote in your question that the file name argument may or may not include the .CustomExtension. Hence I check whether the supplied name ends with the required extension and append it if necessary. Now, since I know what the file name ends with, that means that the required part of the name is everything up to the extension and that's what the call to substring() gives me.
Once I have the required name, I just append the part that you want to append, i.e. -ErrorReport.txt.
Method getParentFile() in class java.io.File returns the directory that the file is located in. Hence I have the directory that the input file is in. Finally I can create the error report file in the same directory as the input file and with the desired file name. For that I use the constructor of class java.io.File that takes two parameters. Read the javadoc for details.
Note that creating a File object does not create the file. Creating an object to write to the file does, for example FileWriter or OutputStreamWriter.
Here is the code example to create a file, with filename passed from cmd line as argument and to get the same file name :
Class Demo{
public static void main(String[]args){
String path ="<path of file>"
String name= args[0];
File f = new File(path+name+".txt");
f.createNewFile(); //create file
System.out.println(f.getName()); // will give you the file name
}
}
cmd line : java -cp . Demo.java <filename>
Note : '.' used in the cmd if your class file is present in current dir
You can refer the code and modify to suit your requirement.
Hope this is what you are looking for.
I'm trying to get my program to read data from a text file and store it in an array. The text file contains data about a planet.
Here is an example:
Mercury
4.151002e10
2.642029e10
-1.714167e9
-3.518882e4
4.355473e4
6.785804e3
3.302e23
My file is named test.txt. It lives in the same directory as my class.java file. I've used System.out.println(new File("test.txt").getAbsolutePath()); to check if the directory path is correct, which it was, and I used System.out.println(new File(".")); to check if it was in the same directory that the code was trying to compile in, which again it was (outputted just a dot which I was led to believe meant it was in the correct directory). I've tried different ways of finding the file, such as renaming it to something else to check it wasn't a keyword, changing the encoding of the file to Unicode, or UTF-8, or ANSI, none of which worked, using .\test in the file to look in the same directory, none of which worked.
Here is my code:
public static void defaultPlanetArray(){
Planet[] solarSystem;
solarSystem = new Planet[9];
PhysicsVector dummyAcceleration = new PhysicsVector();
System.out.println(new File("test.txt").getAbsolutePath());
System.out.println(new File("."));
try{
File file = new File("C:\\Users\\Lizi\\Documents\\Uni Work\\Year 2\\PHYS281\\Project\\test.txt");
Scanner scnr = new Scanner(file);
}
catch(FileNotFoundException e){
System.out.println("File not found!");
}
int i = 0;
while(i<9 && scnr.hasNextLine()){
//read values from file and set as Planet object, then set to array.
i++
}
PhysicsVector and Planet are both classes I have created. PhysicsVector and the rest of Planet apart from this excerpt compile with no problems. When I try to compile this specific bit of code, I get:
.\Planet.java:65: error: cannot find symbol
while(i<9 && scnr.hasNextLine()){
^
I'm guessing this means that the variable scnr is not being created in the try section because it cannot find the file. I think this because when I don't include the try and catch blocks, I get:
.\Planet.java:59: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Scanner scnr = new Scanner(file);
^
I've also tried the catches FileNotFoundException when I'm first creating the method but that gives me the same error as immediately above.
I could just set the values in the program, but that would give a lot of unnecessary code and be rather inefficient I think.
So my question is, how do I get the scanner to read my values from the file?
As #Lalit Verma pointed the scnr variable you defined lives inside the try - catch block.
Change the code to:
try{
File file = new File("C:\\Users\\Lizi\\Documents\\Uni Work\\Year 2\\PHYS281\\Project\\test.txt");
Scanner scnr = new Scanner(file);
int i = 0;
while(i<9 && scnr.hasNextLine()){
//read values from file and set as Planet object, then set to array.
i++
}
}catch(FileNotFoundException e){
System.out.println("File not found!");
}
I wrote a file writing script that lets you write in a file you are looking for in the console, then when you press enter it tries to find the file to see if it exists. My program works, but I don't like that I need the full pathname, every single time. I want a user to just be able to write, say, file_name.txt and the program searches a single directory for it.
Currently, I must use the full pathname every single time. This is not all of my code, but you can see that my file names have a hard coded String pathname. But what if someone else wants to run the program on their own computer? I tried looking for answers to this, but Java is always very difficult for me. If you know a way to make my code generic enough so my Scanner object can take just the file name, that would be so helpful. Thanks, let me know if anything is unclear. I have a Mac, but it should be able to work on any OS.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.util.Scanner;
public class FileHandler {
public static boolean fileCheck = true;
public static File logFile;
public static PrintWriter logPrinter;
public static PrintWriter handMadeFile;
public static LocalDate date = LocalDate.now();
public static File fileFromScanner;
public static File directory = new File("/Users/mizu/homework");
public static String fileName;
public static File file;
public static String created = "Log has been created.";
public static String myLogFileName = "/Users/mizu/homework/my_log.txt";
public static String mainFileName = "/Users/mizu/homework/main_file.txt";
public static String fileFromMethod = "/Users/mizu//homework/file_from_method.txt";
public static String fileMessage = "I just wrote my own file contents.";
public static void main(String[] args) {
if (!directory.exists())
{
// create new directory called homework
directory.mkdir();
}
// gets file request from user
System.out.print("Enter file to find: ");
Scanner in = new Scanner(System.in);
String fileName = in.nextLine();
// initialize the main_file
fileFromScanner = new File(mainFileName);
// if main_file exists or not, print message to my_log
if (!fileFromScanner.exists())
{
// create my_log file (logFile), to keep track of events
writeToLog(created);
writeToLog("File path you entered: "
+ fileName + " does not exist.");
System.out.println(fileName + " - does not exist.");
// create file since it doesn't exist
File mainFile = new File(mainFileName);
try {
PrintWriter pwMain = new PrintWriter(new BufferedWriter
(new FileWriter(mainFile)));
writeToLog("Created " + mainFileName);
pwMain.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
writeToLog(fileName + " already exists.");
System.out.println(fileName + " - already exists.");
}
// use writeToFile method to write file, create new file name
FileHandler testFile = new FileHandler(fileFromMethod);
testFile.writeToFile(testFile, fileMessage);
} // end Main
All of the other methods are below here, but not shown to keep it short.
As stated in the comments, there are several tools already available to search files in a directory. However, to answer your question, I wrote a simple program that should do what you are looking for:
public static void main(String[] args) {
// Get the absolute path from where your application has initialized
File workingDirectory = new File(System.getProperty("user.dir"));
// Get user input
String query = new Scanner(System.in).next();
// Perform a search in the working directory
List<File> files = search(workingDirectory, query);
// Check if there are no matching files
if (files.isEmpty()) {
System.out.println("No files found in " + workingDirectory.getPath() + " that match '"
+ query + "'");
return;
}
// print all the files that matched the query
for (File file : files) {
System.out.println(file.getAbsolutePath());
}
}
public static List<File> search(File file, String query) {
List<File> fileList = new ArrayList<File>();
// Get all the files in this directory
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
// use recursion to search in all directories for the file
fileList.addAll(search(f, query));
} else if (f.getName().toLowerCase().contains(query.toLowerCase())) {
// if the filename matches the query, add it to the list
fileList.add(f);
}
}
}
return fileList;
}
1- You can make users set an environment variable to your path and use the path name in your code.
2- You can check the operating system, and put your files in a well-known folder. (C: for windows, /home for Ubuntu, /WhateverMacFolder for mac and if it is some other os ask user to enter the path.
3- You can create a folder in default path of your program and use it.
Java newbie here!
I'm writing a program to practice reading input and writing output to files. I've finished coding the program, but when I run it, the program just catches and proceeds with a FileNotFoundException.
The file is in the source folder for the program, and I've even tried placing it in every folder related to the program. I've tried:
Declaring the exceptions in the method header
Surrounding the section-in-question with a try/catch block.
Both of the above together.
Here's the relevant code that is causing problems. Is there something that sticks out that I'm missing?
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
String playerHighestScore = "", playerLowestScore = "";
int numPlayers = 0, scoreHighest = 0, scoreLowest = 0;
System.out.println("Enter an input file name: ");
String inputFileName = keyboard.nextLine();
String outputFileName = getOutputFileName(keyboard, inputFileName);
File inputFile = new File(inputFileName);
try {
Scanner reader = new Scanner(inputFile);
reader.close();
}
catch (FileNotFoundException exception) {
System.out.println("There was a problem reading from the file.");
System.exit(0);
}
Scanner reader = new Scanner(inputFile);
PrintWriter writer = new PrintWriter(outputFileName);
The answer is simple. If you get a FilENotFoundException, obviously the reason is File Not Found in the given path.
If you use an IDE, path for the working directory is different from the source directory.
For example, if you are using NetBeans, your source files are inside /src. But your working directory (.) is the project directory.
In the other hand, the problem may be the thing that #Don mentioned. If you are going for a cross platform approach, you can use "/" in paths. It works irrespective to the OS.
Example : String fileName = "C:/Directory/File.txt";
And these paths are case sensitive. So make sure you use the correct case. (It won't be a problem in Windows, until you package the program.)
I have a file which is needed for running tests - this file needs to be personalized (name and password) by whomever is running the test. I do not want to store this file in Eclipse (since it would need to be changed by whomever runs the test; also it would be storing personal info in the repo), so I have it in my home folder (/home/conrad/ssl.properties). How can I point my program to this file?
I've tried:
InputStream sslConfigStream = MyClass.class
.getClassLoader()
.getResourceAsStream("/home/" + name + "/ssl.properties");
I've also tried:
MyClass.class.getClassLoader();
InputStream sslConfigStream = ClassLoader
.getSystemResourceAsStream("/home/" + name + "/ssl.properties");
Both of these give me a RuntimeException because the sslConfigStream is null. Any help is appreciated!
Use a FileInputStream to read data from a file. The constructor takes a string path (or a File object, which encapsulates string path).
Note 1: A "resource" is a file which is in the classpath (alongside your java/class files). Since you don't want to store your file as a resource because you don't want it in your repo, ClassLoader.getSystemResourceAsStream() is not what you want.
Note 2: You should use a cross-platform way of getting a file in a home directory, as follows:
File homeDir = new File(System.getProperty("user.home"));
File propertiesFile = new File(homeDir, "ssl.properties");
InputStream sslConfigStream = new FileInputStream("/home/" + name + "/ssl.properties")
You can simplify your work, using Java's 7 method:
public static void main(String[] args) {
String fileName = "/path/to/your/file/ssl.properties";
try {
List<String> lines = Files.readAllLines(Paths.get(fileName),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
You can also improve your way of reading properties file, using Properties class and forget about reading and parsing your .properties file:
http://www.mkyong.com/java/java-properties-file-examples/
Is this a graphics program (ie. using the Swing library)? If so it is a pretty simple task of using a JFileChooser.
http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html
JFileChooser f = new JFileChooser();
int rval = f.showOpenDialog(this);
if (rval == JFileChooser.APPROVE_OPTION) {
// Do something with file called f
}
You can also use Scanner to read the file.
String fileContent = "";
try {
Scanner scan = new Scanner(
new File( System.getProperty("user.home")+"/ssl.properties" ));
while(scan.hasNextLine()) {
fileContent += scan.nextLine();
}
scan.close();
} catch(FileNotFoundException e) {
}