I have a question about txt file in the Java
When I have to read the text file, i have to point out the path.
However, txt file is in the same folder.
What need to do is...
testing readingoption filename.
testing : class name
readoption : option for reading file
filename: file name that same folder.
However, I don't want to use path to pointing out the file which means that I want to read the text file without using "C:/Users/myname/Desktop/myfolder/" in my code.
does anybody know how to do it ?
thanks.
public class testing{
private static boolean debug = true;
public static void main(String args [])
{
if(args.length == 0)
{// if you do nothing
if(debug == true)
{
System.out.println(args);
}
System.err.println("Error: Missing Keywords");
return;
}
else if(args.length == 1)
{// if you miss key word
if(debug == true)
{
System.out.println(args);
}
System.err.println("Error: Missing filename");
return;
}
else
{// if it is fine
String pathes = "C:/Users/myname/Desktop/myfolder/";// dont want to use this part
if(debug == true)
{
System.out.println("Everthing is fine");
System.out.println("Keyword :" + args[0]);
System.out.println("File name :" + args[1]);
}
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(pathes + "bob.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
}
Change this line String pathes = "C:/Users/myname/Desktop/myfolder/"; to:
String pathes = args[1];
and this line FileInputStream fstream = new FileInputStream(pathes + "bob.txt"); to:
FileInputStream fstream = new FileInputStream(pathes);
If you put text file into i.e. "myfolder" in your java project your path should be like this:
String pathes = "/myfolder/bob.txt";
FileInputStream fstream = new FileInputStream(pathes);
Load the path of the file from a .properties file (use the java.util.Properties class), or pass it as a parameter from commandline (in your main String[] argument).
Either way, your code that processes the file must not do it, it must be done in the outside. Your processing code receives the file path from the method calling it, so you do not need to change if you decide to use another method (v.g., a GUI).
You can use "." for the actual Path and add the system dependend file seperator like:
FileInputStream fstream = new FileInputStream("."+System.getProperty("file.separator")+"bob.txt");
Related
I have a text file in the same location as my .jar program:
Main Folder:
|_ myJar.jar
|_ myText.txt
When I run the .jar file I would like it to read the contents of myText.txt, however with the path set as String fileName = "./Paths.txt"; it still doesn't read the file. I believe it's trying to read the Paths.txt file from inside the jar.
I tried other solutions, none seem to tell the program to read the Paths.txt file from outside of the jar file, so any help would be greatly appreciated.
Code:
public static void readFile() {
String fileName = "./Paths.txt";
BufferedReader br;
String line;
//Attempts to read fileName
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
try {
// Starts reading the file and adding values to linked hashmap
while ((line = br.readLine()) != null) {
String[] lineSplit1 = line.split("#");
String lineKey = lineSplit1[0];
String lineValue = lineSplit1[1];
hm.put(lineKey, lineValue);
}
} catch(Exception e3) {
errorMessage("Error when trying to read the file and add "
+ "the values to a hashmap");
}
//Attempts to close fileName
try {
br.close();
} catch(IOException e1 ) {
System.out.println("Messed up while trying to close buffered reader");
System.out.println(e1);
}
} catch (FileNotFoundException e1) {
errorMessage("The file " + fileName + " does not exist"
+ "\nI have created the file for you.");
try {
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println("");
writer.close();
} catch(Exception e2) {
errorMessage("Error while trying to create " + fileName);
}
}
}
I suppose, you can get a full path to your file, just need to initialize it, via your Class, which should be packaged in myJar.jar. Just change YourClass in the example to some real Class from your jar.
public static void readFile() {
File file = new File(YourClass.class.getProtectionDomain().getCodeSource().getLocation().getFile());
String fileName = file.getParent() + File.separator + "Paths.txt";
...
I know previous questions LIKE this one have been asked, but this question has to do with the specifics of the code that I have written. I am trying to update a single line of code on a file that will be permanently updated even when the program terminates so that the data can be brought up again. The method that I am writing currently looks like this (no compile errors found with eclipse)
public static void editLine(String fileName, String name, int element,
String content) throws IOException {
try {
// Open the file specified in the fileName parameter.
FileInputStream fStream = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(
fStream));
String strLine;
StringBuilder fileContent = new StringBuilder();
// Read line by line.
while ((strLine = br.readLine()) != null) {
String tokens[] = strLine.split(" ");
if (tokens.length > 0) {
if (tokens[0].equals(name)) {
tokens[element] = content;
String newLine = tokens[0] + " " + tokens[1] + " "
+ tokens[2];
fileContent.append(newLine);
fileContent.append("\n");
} else {
fileContent.append(strLine);
fileContent.append("\n");
}
}
/*
* File Content now has updated content to be used to override
* content of the text file
*/
FileWriter fStreamWrite = new FileWriter(fileName);
BufferedWriter out = new BufferedWriter(fStreamWrite);
out.write(fileContent.toString());
out.close();
// Close InputStream.
br.close();
}
} catch (IOException e) {
System.out.println("COULD NOT UPDATE FILE!");
System.exit(0);
}
}
If you could look at the code and let me know what you would suggest, that would be wonderful, because currently I am only getting my catch message.
Okay. First off the bat, StringBuilder fileContent = new StringBuilder(); is bad practice as this file could well be larger than the user's available memory. You should not keep much of the file in memory at all. Do this by reading into a buffer, processing the buffer (adjusting it if necessary), and writing the buffer to a new file. When done, delete the old file and rename the secondary to the old one's name. Hope this helps.
So I'm trying to delete a line of data from a file, which I have successfully done by opening a new file and writing all the information that doesn't match with the data that I would like to remove. The problem is, after I have done that, I would like to delete my original file, and then rename the new file with excludes the information I wanted to delete, to the same name as the original file. I have added in the code to do this, but for some reason it's not working.
public static void delete() throws IOException
{
File inputFile = new File("Elements.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String element = JOptionPane.showInputDialog(null, "Enter the name of the Element you wish to delete.", "Remove an Element.", JOptionPane.INFORMATION_MESSAGE);;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(element)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete();
tempFile.renameTo(inputFile);
JOptionPane.showMessageDialog(null, "Data has been removed from the file: Elements.txt");
}
As you can see near the bottom, I have these lines:
inputFile.delete();
tempFile.renameTo(inputFile);
These lines are meant to delete my original file(inputFile) and then rename my new file(tempFile) to the file name that the original file had. After running the code however, I simply get a file called "myTempFile.txt" which has succesfully deleted the line of data that I wanted, but my original file is still present and it wasn't deleted, neither was the new file renamed to the original file.
Any idea why this is happening?
Use the java.nio.file API. This is 2015.
final Path src = Paths.get("Elements.txt").toAbsolutePath();
final Path tmp = src.resolveSibling("Elements.txt.new");
try (
final BufferedReader reader = Files.newBufferedReader(src, StandardCharsets.UTF_8);
final BufferedWriter writer = Files.newBufferedWriter(tmp, StandardCharsets.UTF_8,
StandardOpenOption.CREATE_NEW);
) {
// yadda yadda
}
Files.move(tmp, src, StandardCopyOption.REPLACE_EXISTING);
File is unreliable. It has always been.
in such a case i would start fiddling around, reading documentation and maybe googling for a bit. But i will give you an answer, too!
inputFile.delete();
This could go wrong, for example if you have your file opened in a text editor.
Luckily delete() returns a boolean, try checking that!
Also as Niels correctly mentioned File.renameTo() is quite unrelieble if you have access to Java 7 use the files.nio alternative. In Java 7 you can use Files.move(Path source, Path target, CopyOption... options)
Docs for Java 7 Files: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
But your very code works correctly for me. I only change the path to the file and I make sure the file is not opened in editor
public class NewClass {
public static void main(String[] args) {
try {
delete();
} catch (IOException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void delete() throws IOException {
File inputFile = new File("C:\\Users\\olyjosh\\Desktop\\Elements.txt");
File tempFile = new File("C:\\Users\\olyjosh\\Desktop\\myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String element = JOptionPane.showInputDialog(null, "Enter the name of the Element you wish to delete.", "Remove an Element.", JOptionPane.INFORMATION_MESSAGE);;
String currentLine;
while ((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if (trimmedLine.startsWith(element)) {
continue;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete();
tempFile.renameTo(inputFile);
JOptionPane.showMessageDialog(null, "Data has been removed from the file: Elements.txt");
}
}
So the following program should take in an input and output file as command line arguments. I'm entering in java FileCopy input.txt output.txt on the command line to run the program, which should put the file names in args. Testing this, I don't have any values in args. On top of this, method calls to fileExists() are not working, and I can't figure out why these calls aren't being executed. As a note, the getOutputFile method is incomplete, none of the code there currently gets executed due to the errors stated above.
class FileCopy
{
public static void main(String[] args) throws IOException
{
String infile = null;
String outfile = null;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
if (args.length >= 2) //both files given via command line
{
infile = args[0];
if (fileExists(infile) == false)
{
infile = getInputFile();
}
outfile = args[1];
}
else if (args.length == 1) //input file given via command line
{
infile = args[0];
outfile = getOutputFile(infile);
}
else //no files given on command line
{
infile = getInputFile();
outfile = getOutputFile(infile);
}
//create file objects to use
File in = new File(infile);
File out = new File(outfile);
/*
*rest of code
*/
}
//get the input file from the user if given file does not exist
public static String getInputFile() //throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
boolean haveFile = false;
while(haveFile == false)
{
System.out.println("Enter a valid filename for input:");
System.out.print(">> ");
try
{
fileName = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
haveFile = fileExists(fileName);
}
return fileName;
}
//get the output file and test things
public static String getOutputFile(String infile)
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
File input = new File(infile);
String filename = null;
boolean more = true;
while(more)
{
System.out.println("Enter a valid filename for output:");
System.out.print(">> ");
try
{
filename = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
File output = new File(filename);
if (output.exists())
{
more = false;
}
if (filename == infile)
{
int selection;
String inputString = null;
System.out.println("The output file given matches the input file. Please choose an option:");
System.out.println("1) Enter new filename");
System.out.println("2) Overwrite existing file");
System.out.println("3) Backup existing file");
System.out.print(">> ");
try
{
inputString = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
selection = Integer.valueOf(inputString);
switch (selection)
{
case 1: //new filename
case 2: //overwrite
case 3: //backup
default: System.exit(0);
}
}
}
return null;
}
//check the given file to see if it exists in the current working directory
public static boolean fileExists(String n)
{
return (new File(n)).exists();
}
}
just tested this in eclipse debugger and the commandline arguments are correctly placed in args, you may check if the file you test with are in your project folder or actual dir "." because if not it will otherwise prompt for new files anyway
if (fileExists(infile) == false)
{
infile = getInputFile();
}
Shouldn't the class be public?
public class FileCopy
Not sure if that will solve the problem or not.
You will need to enter a fully qualified path, depending on your project's structure. In my test environment, it defaults to the root level of the project in the IDE. Normally, the new File(n) call will default to the system-dependent default directory. I did compile and run this from a single directory with no package and was able to use the abstract file names successfully (i.e. input.txt and output.txt). Is there any harm in forcing users to supply full qualified file names or at least only ever check the args values. This would allow you to fail early on invalid arguments, rather than having to worry about prompting the users for additional filenames.
I have a method like this:
public int getIncrement() {
String extractFolder = "/mnt/sdcard/MyFolder";
boolean newFolder = new File(extractFolder).mkdir();
int counter = 0;
try {
File root = new File(extractFolder);
if (root.canWrite()){
File gpxfile = new File(root, "gpxfile.txt");
FileWriter gpxwriter = new FileWriter(gpxfile);
BufferedWriter out = new BufferedWriter(gpxwriter);
Scanner scanner = new Scanner(new FileInputStream(gpxfile.getAbsolutePath()), "UTF-8");
Log.i("PATH: ", extractFolder + "/gpxfile.txt");
while(scanner.hasNextLine()) {
String inc = scanner.nextLine();
counter = Integer.parseInt(inc);
Log.i("INSIDE WHILE: ", Integer.toString(counter));
}
counter++;
out.write(Integer.toString(counter));
out.close();
}
} catch (IOException e) {
Log.e("GEN_PCN: ", "Could not write file " + e.getMessage());
}
return counter;
}
What I am trying to accomplish is returning the content of this file, and increment the integer by 1. But it seems that I can't get in the while loop, because LogCat doesn't print out anything. Yes, am sure that the path is correct.
I guess the constructor of FileWriter gpxwriter has already blanked out the file by the time the Scanner is created, so the file is empty and hasNextLine returns false. Why do you open a file for writing when you want to read it?
From what I can tell the file doesn't exist. Try adding gpxfile.createNewFile()
To get a little more in depth, creating a File instance, does not create a file on the file system.
So, this line -> File gpxfile = new File(path, filename);
is not sufficient to create the file on the sd card. You must follow it with
gpxfile.createNewFile() which quoting the docs says:
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
OK I MARK YOUR FILE NAME
Just add a BACKSLASH in extractFolder at END
v
v
v
String extractFolder = "/mnt/sdcard/MyFolder/";
^ // <--- HERE
^
^
Because File gpxfile = new File(root, "gpxfile.txt"); doesn't have BackSlash / as Log have
Just try Once Following:
while(scanner.hasNextLine()) {
String inc = scanner.nextLine();
// // counter = Integer.parseInt(inc);
Log.i("INSIDE WHILE: ", inc);
System.out.println("Next Line ::"+inc); // Also check this
}