File input/output [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Ive been asked my current program to be saved into a file so it can be continued later even if the program end. However I am new to java, so I Would really appreciate if someone can help me on this :) This is the code i manage to get done, however it just creates an empty file,how am I suppose to go about this problem?
Below is not the whole program coding, i've just copied the codes that is relevant.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileWriter;
public static void main (String[] param) throws FileNotFoundException
{
try
{
fileinputoutput ();
}
catch (FileNotFoundException e)
{
System.exit(0);
}
} // END main
public static void fileinputoutput() throws FileNotFoundException
{
File input = new File("input.txt");
File output = new File("loveletter.txt");
PrintWriter outputFile = new PrintWriter(output);
Scanner check = new Scanner(System.in);
String filename = check.nextLine();
File inputfile = new File(filename);
Scanner newfile = new Scanner(inputfile);
newfile.close();
while(newfile.hasNext())
{
String write = newfile.nextLine();
System.out.println(write);
}
outputFile.close();
}

The answer is pretty obvious. The reason why you only get a blank file is that you never write anything through outputFile and close newfile before you can do anything with it. You should try something like this:
public static void fileinputoutput() throws FileNotFoundException {
File input = new File("input.txt"); // What do you use this variable for? It's never used in the code fragment you posted
File output = new File("loveletter.txt");
PrintWriter outputFile = new FileWriter(output); // I'd personally use FileWriter here
Scanner check = new Scanner(System.in);
String filename = check.nextLine();
File inputFile = new File(filename);
Scanner newfile = new Scanner(inputFile);
while(newfile.hasNext()) {
String write = newfile.nextLine();
outputFile.println(write); // You used to only output something to the console here
}
outputFile.close();
newfile.close();
check.close();
}

Related

How can I let user input the name of text file again if the name of file already exists?

public static void textFileOpen(String fileName) throws IOException
{
while(true)
{
try
{
FileReader fileReader = new FileReader(fileName);
LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
BufferedReader bufferedReader = new BufferedReader(fileReader);
fileReader.close();
bufferedReader.close();
lineNumberReader.close();
}
catch(Exception ex)
{
System.out.println("File " + fileName + " does not exists! Please try again.");
}
}
}
I'm trying to let the user input file name again if exists. But it runs forever if user enter an exist file name. How can I fix it? Can anyone help, please? THank you
The cause is your use of try(input). As the scanner has already been closed after the first catch , it is not able to take any new input.
Remove the (input) and use a separate input.close should work.
You shouldn't close a Scanner that wraps System.in since System.in represents the standard input which is generally the computer keyboard. So when you close it, your program cannot receive input from the keyboard.
You should also not use exception handling to test a condition. You should use a conditional statement, like an if statement.
In order to test whether a file exists, you can call method isFile. The method returns...
true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise
When you create a FileWriter, it also creates the file if it doesn't already exist.
Here is code demonstrating the above.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Cipher {
public static void main(String[] args) throws IOException {
System.out.println("Enter fileName: ");
Scanner input = new Scanner(System.in);
String fileName = null;
File file = null;
while (true) {
fileName = input.nextLine();
file = new File(fileName);
if (file.isFile()) {
System.out.println(file + " already exists! Please try again:");
}
else {
break;
}
}
FileWriter writer = new FileWriter(file);
}
}

Can't read txt file with Scanner in Eclipse (Java)

I'm having difficulty reading a .txt file (words.txt) for a project I'm working on within Eclipse (jre1.8.0_181). I have a copy of words.txt in
String wordsPath = "C:\\Users\\Administrator\\Documents\\words.txt";
as well as in the project directory itself (which I tried to define multiple ways):
String workingDir = System.getProperty("user.dir");
String wordsPath2 = workingDir.concat("\\words.txt");
String wordsPath3 = new File("").getAbsolutePath().concat("\\words.txt");
However, when I attempt to establish filein:
Scanner filein = new Scanner(new File(wordsPath));
filein = new Scanner(new File(wordsPath2));
filein = new Scanner(new File(wordsPath3));
I get a FileNotFoundException on all attempts. Does anybody have any insight into this? I know the files are there; what else am I missing? I have the right imports as well, I believe (import java.io.File; and import java.util.Scanner;). I looked through as many similar questions I could find, no luck. Many thanks!
Both files in below program can be read without any error. Compare and see whether you are doing something wrong.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile
{
public static void main(String[] args)
{
try
{
Scanner scanner = new Scanner(new File("words.txt"));
System.out.println(scanner.nextLine());
System.out.println(scanner.nextLine());
Scanner scanner2 = new Scanner(new File("C:\\Users\\prasad.karunagoda\\words2.txt"));
System.out.println(scanner2.nextLine());
System.out.println(scanner2.nextLine());
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
}
}

possible i can let my user to name the text file themself? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
normally we write the file writer command with provide the file path and also the name of the text file for user.
example: create a assignment text file
FileWriter writer = new FileWriter(".......\assignment");
but is it possible that let my user to name the text file them self?
because my program need let lecturer enter bibliographic details about the key reading for an assignment, so lecturer can name the text file by the name with assignment.
Using a try-with-resources you might pass a user provided String to the FileWriter(String) constructor with something like,
public static void main(String[] args) {
System.out.println("Please enter a file name: ");
Scanner scan = new Scanner(System.in);
String str = scan.next();
try (FileWriter writer = new FileWriter(str)) {
} catch (IOException e) {
e.printStackTrace();
}
}
Edit
To use a file in the user's home directory, you might use
try (FileWriter writer = new FileWriter(new File(
System.getProperty("user.home"), str))) {
} catch (IOException e) {
e.printStackTrace();
}
I guess your writing a console application, not a GUI one.
In this case use something like the following:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileChooser {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter(chooseFile());
// Use your FileWriter
}
public static File chooseFile() {
String fname = null;
File file = null;
System.out.println("Please choose file name:");
while (true) {
try (Scanner in = new Scanner(System.in)) {
// Reads a single line from the console
fname = in.nextLine();
file = new File(fname);
if (!file.createNewFile()) {
throw new RuntimeException("File already exist");
}
break;
} catch (Exception ex) {
System.out.println(ex.getMessage() + ", please try again:");
}
}
return file;
}
}
EDIT
If you are writing a Swing GUI, you can use JFileChooser:
//Create a file chooser
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(parentComponent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
} else {
// User canceled the file chooser.
}
You can use Scanner to get the file name from the keyboard. If you are using command prompt for taking file name then you can use the following code -
Scanner input = new Scanner(System.in);
String fileName = input.next();
Then pass the 'fileName' to the PrintWriter constructor.
PrintWriter writer = new PrintWriter(fileName);
writer.close();

Java.IO.Filenotfoundexception error, Can't find a file that exists in C:

I am recently beginning programming and cannot get my program to find a file, then read input from it. Says the file does not exist. Here is my code.
import java.util.*;
import java.io.*;
public class assignment3 {
public static void main(String args[]) throws IOException {
PrintWriter pw = new PrintWriter("C:\\file\\Summary.txt");
Scanner k = new Scanner(System.in);
String filename;
System.out.println("--------------------------------\nBowsers Nuclear Weapons Inventory\n" +
"---------------------------------");
System.out.print("Please enter the name of the file: ");
filename = k.next();
File f = new File(filename);
System.out.println(f);
Scanner inputFile = new Scanner(f);
String Game1 = inputFile.nextLine();
System.out.println(Game1);
inputFile.close();
}
}
At line Scanner inputfile = new Scanner(f);. The error mentioned appears. Also when prompted to type in the file name in the program, i put "C:/Games.txt".....but when i got the filename to be printed out the filename is registerd as C:\Games.txt....why is the forward slash turning into a backslash. Thank you for taking the time to help me.
Make sure the folder named "file" exists (for creating a file). It might throw that error if it's not there. For reading you need to have the proper rights.
why is the forward slash turning into a backslash?
Because you're on Windows, and directories are natively separated by a \
Next, you don't appear to be writing with your PrintWriter. And if you want to check for a file that exists, call File#exists().
File f = new File(filename);
if (f.exists()) {
System.out.println(f);
Scanner inputFile = new Scanner(f);
while (inputFile.hasNextLine()) {
System.out.println(inputFile.nextLine());
}
} else {
System.out.println(f.getPath() + " does not exist");
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Answer {
public static void main(String args[]) throws IOException, FileNotFoundException {
// Have to throw a FileNotFoundException just in case an error occurs the compiler needs to know how to process the error.
PrintWriter pw = new PrintWriter("C:/file/Summary.txt");
Scanner k = new Scanner(System.in);
String filename;
System.out
.println("--------------------------------\nBowsers Nuclear Weapons Inventory\n"
+ "---------------------------------");
System.out.print("Please enter the name of the file: ");
filename = k.nextLine(); //Input for strings
System.out.println(filename);
File f = new File("C:/file/"+filename+".txt"); //Must have a location for your files
f.createNewFile(); //The file's pathname is the only thing that you can supply when you instantiate the object
//you actually have to invoke the createNewFile method upon the object.
if(f.exists()) { //Don't be afraid to check your code this is a must for every programmer.
System.out.println("Good! The File Exists");
}
Scanner inputFile = new Scanner(f);
String Game1 = inputFile.nextLine();
System.out.println(Game1);
inputFile.close();
}
}
When you create a file you always have to throw a FileNotFoundException if you do not the compiler will not know what to do if the error occurs. Use / when specifying directories of files.
\ is generally used as an escape sequence and when you type this \ \ your basically telling it to escape itself this code is useful in other situations but not this one.
You can NOT create a new file by the initiation of the object you always have to invoke the createNewFile method upon the object so that you can create a new file. This is because no constructors automatically call the createNewFile method in the class. You might be wondering what the words in the parameter are, they just serve the purpose of naming the file directory. I have found a helpful link if you want to review creating Files. Just look under the constructors tab. API Files Class
BE SURE! to always check your code, it does not matter how good of a programmer you are. You ALWAYS have to check for errors and if you make a game, and don't know where the error is among the millions of lines of code. You are going to have a hell of a time.
Lastly, I was not sure what you were trying to do after the if statement, but you will receive an error after the if statement, so if you want to ask me how to help with that just type in the comments of my post.

Modifying Output in String Input By Text File (Java) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
thanks to everyone in advance.
I have lines of strings input through a text file and would like to modify the output to remove the last two letters of each string. This is what the text file currently reads:
hello how are you
cool
i am amazing
and this is the code I'm using (from Java-tips.org)
package MyProject
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* This program reads a text file line by line and print to the console. It uses
* FileOutputStream to read the file.
*
*/
public class FileInput {
public static void main(String[] args) {
File file = new File("MyFile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
// this statement reads the line from the file and print it to
// the console.
System.out.println(dis.readLine());
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The code works perfectly, but I'd like to modify the output to remove the last two letters of each string (string = one per line) Thanks everyone!
Here's my recommendation. Don't use streams for something so trivial and non-load intensive. Stick to the basics, use a Scanner and read your file line-by-line.
Here's the method to success!
Learn how to use a Scanner to read Strings from a text file line-by-line.
Make sure you split the Strings apart with the str.split() method accordingly.
Store each line's String value into a array/list/table.
Modify your stored Strings to remove the last two letters. Look into the str.subString(s,f) method.
Learn how to use a PrintWriter to output your modified Strings to a file.
Good luck!
Comment Reply
Read in a line as a String from texfile.
File file = new File("fileName.txt");
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine(); //<------This is a String representation of a line
System.out.println(line); //prints line
//Do your splitting here of lines containing more than 1 word
//Store your Strings here accordingly
//----> Go on to nextLine
}

Categories

Resources