User Input File Console/Command Line - Java - java

Most examples out there on the web for inputting a file in Java refer to a fixed path:
File file = new File("myfile.txt");
What about a user input file from the console? Let's say I want the user to enter a file:
System.out.println("Enter a file to read: ");
What options do I have (using as little code as possible) to read in a user specified file for processing. Once I have the file, I can convert to string, etc... I'm thinking it has to do with BufferedReader, Scanner, FileInputStream, DataInputStream, etc... I'm just not sure how to use these in conjunction to get the most efficient method.
I am a beginner, so I might well be missing something easy. But I have been messing with this for a while now to no avail.
Thanks in advance.

To have the user enter a file name, there are several possibilities:
As a command line argument.
public static void main(String[] args) {
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
}
By asking the user to type it in:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);

Use a java.io.BufferedReader
String readLine = "";
try {
BufferedReader br = new BufferedReader(new FileReader( <the filename> ));
while ((readLine = br.readLine()) != null) {
System.out.println(readLine);
} // end while
} // end try
catch (IOException e) {
System.err.println("Error Happened: " + e);
}
And fill the while loop with your data processing.
Regards,
Stéphane

Related

java copying all contents of one file to another using input to read/create the file name

I'm having trouble using input to create the file that I want to write the lines from another file in. When my code reaches the file name I want to create, it doesn't let me input anything after I inputted the filename for file I want to open. I thought that this had something to do with the scanner not being able to take in the last "\n" or something so I tried to "flush" it with sc.nextLine() after the first time I called it but it didn't work. I don't really understand the logic of the system not working for the second nextLine(), shouldn't it be the same as the first one? Can someone explain please?
try {
System.out.println("Enter the file name to open with extension: ");
Scanner sc = new Scanner(System.in);
File file = new File(sc.nextLine());
sc = new Scanner(file); //opens inputted file name
// System.err.println(file.getAbsolutePath());
System.out.println("What is the file name you want to create? ");
// sc.nextLine();
File write = new File(sc.nextLine());
PrintWriter writer = new PrintWriter(write);
// System.out.println("Copying file contents over... ");
while (sc.hasNextLine()) {
String line = sc.nextLine();
writer.println(line);
}
writer.close();
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try this:
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the file name to open with extension: ");
File file = new File(br.readLine());
Scanner sc = new Scanner(file); //opens inputted file name
System.out.println("What is the file name you want to create? ");
File write = new File(br.readLine());
PrintWriter writer = new PrintWriter(write);
while (sc.hasNextLine()) {
String line = sc.nextLine();
writer.println(line);
}
writer.close();
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Java Scanner null out put

I'm using Scanner to read a file with different extension that a text file normally has but with same content as text file.
If I do use Scanner on text.txt extension then I do get out put but when I perform same task on the different extension but with same content that I don't get any output at all.
After performing different test, it seen that the problem are those characters: “ ”
Any clue why same file with different extension got different behaviors?
file:
“1 line”
2nd line
3 rd line
code:
public static void main(String[] args)
{
String path = "C:\\Users\\user\\Documents\\t1.RANDOM";
File file = new File(path);
StringBuilder sb = new StringBuilder();
try {
Scanner sc = new Scanner(file);
while(sc.hasNextLine())
{
sb.append(sc.nextLine()+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(sb);
}
I might think Scanner is doing different stream reading if it doesn't identify a known extension.
Maybe try using the following constructor:
Scanner sc = new Scanner(file, "UTF-8");

readfile in from text file elements java

I'm trying to read in a .txt file in but when i use debugger it gets stuck on nextline? Is there some logic error that im doing? It's all being stored into an array through multiple objects:
public static File readFileInfo(Scanner kb)throws FileNotFoundException
{
System.out.println("Enter your file name");
String name = "";
kb.nextLine();
name = kb.nextLine();
File file = new File(name);
return file;
}
The scanner I passed into it is:
Scanner fin = null, kb = new Scanner(System.in);
File inf = null;
inf = FileUtil.readFileInfo(kb);
fin = new Scanner(inf);
You're reading from two different "files" here:
System.in, the standard input (or "terminal"), which you're using to ask the user for a filename
the file with the name you get from the user
When you call name = kb.nextLine();, you're asking the parameter (the Scanner built with System.in) for its next line. Generally, that will actually block ("hang") until it receives another line of input (the filename) from the user. If running from a command line, enter your text into that window; if running in an IDE, switch to the Console tab and enter it there.
As quazzieclodo noted above, you probably only need to call readLine once.
After that, you can open up your second Scanner based on the File that readFileInfo returns, and then you're actually reading from a text file as expected.
Assuming that your intention is to use Scanner to read a text file:
File file = new File("data.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

extract matched line from text file

a:b:c:d:e
bb:cc:dd:ee:ff
ccc:ddd:eee:fff:ggg
I have a textfile content above. I am trying to compare my user input with the text file. For example
cc:dd
When it is found, I need to retrieve the entire line. How can I retrieve the line which my user input? I have tried using while(scanner.hasNext()) but I could not get my desire outcome.
With standard Java libraries:
File file = new File("file.txt");
String word = "abc";
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch(FileNotFoundException e) {
//handle this
}
//now read the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains(word)) {
System.out.println(line);
}
}
scanner.close();

Reading and displaying data from a .txt file

How do you read and display data from .txt files?
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
If your file is strictly text, I prefer to use the java.util.Scanner class.
You can create a Scanner out of a file by:
Scanner fileIn = new Scanner(new File(thePathToYourFile));
Then, you can read text from the file using the methods:
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
And, you can check if there is any more text left with:
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Once you have read the text, and saved it into a String, you can print the string to the command line with:
System.out.print(aString);
System.out.println(aString);
The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.
In general:
Create a FileInputStream for the file.
Create an InputStreamReader wrapping the input stream, specifying the correct encoding
Optionally create a BufferedReader around the InputStreamReader, which makes it simpler to read a line at a time.
Read until there's no more data (e.g. readLine returns null)
Display data as you go or buffer it up for later.
If you need more help than that, please be more specific in your question.
I love this piece of code, use it to load a file into one String:
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
If you want to take some shortcuts you can use Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
You most likely will want to use the FileInputStream class:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.

Categories

Resources