Java read file using Scanner - java

I can read file using java.io and java.util.Scanner but I don't know how to read file using only java.util.Scanner:
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
String filePath = "C:\\IdeaProjects\\test\\src\\input.txt";
Scanner sc = new Scanner(new File(filePath));
int a, b;
a = sc.nestInt();
b = sc.nextInt();
}
}
Can someone help?

Since Scanner requires a java.io.File object, I don't think there's a way to read with Scanner only without using any java.io classes.
Here are two ways to read a file with the Scanner class - using default encoding and an explicit encoding. This is part of a long guide of how to read files in Java.
Scanner – Default Encoding
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile_Scanner_NextLine {
public static void main(String [] pArgs) throws FileNotFoundException {
String fileName = "c:\\temp\\sample-10KB.txt";
File file = new File(fileName);
try (Scanner scanner = new Scanner(file)) {
String line;
boolean hasNextLine = false;
while(hasNextLine = scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
}
}
}
}
Scanner – Explicit Encoding
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile_Scanner_NextLine_Encoding {
public static void main(String [] pArgs) throws FileNotFoundException {
String fileName = "c:\\temp\\sample-10KB.txt";
File file = new File(fileName);
//use UTF-8 encoding
try (Scanner scanner = new Scanner(file, "UTF-8")) {
String line;
boolean hasNextLine = false;
while(hasNextLine = scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
}
}
}
}

if you want to read the file until the end:
String filePath = "C:\\IdeaProjects\\test\\src\\input.txt";
File file = new File(filePath);
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
p.s If every line have only Integer I suggest you to use
Integer.parseInt(sc.readLine());
instead of sc.nextInt();
If you cant read please send me file Context

Well, if you are using a Mac, you type this into the terminal file.java<input.txt and to output to a file you type this: file.java>output.txt output.txt is a non-existing file, while input.txt is a pre-existing file.

Related

My java scanner doesn't seem to be reading my input (.txt file)

I am new to Java, and I am learning how to read input using Java on Eclipse. I am using a scanner to read a .txt input file, however, it doesn't seem to be reading the very first integer in the .txt file.
Here is the .txt file:
2 1 4
Here is my simplified code:
public class Test {
static int var;
static int[] arr;
public static void main(String[] args) {
String fileName = "/Users/anon/eclipse-workspace/Lab/src/input-01.txt";
readInput(fileName);
}
public static void readInput(String fileName) {
File file = new File(fileName);
Scanner fileInput = new Scanner(file);
//Read T
var = fileInput.nextInt();
System.out.printf("var: %d", var);
arr = new int[var];
}
I tried debugging, and I realized that "int var" never even appeared in the variables table on the right -- so I am not sure if "int var" was even initialized at all.
Please let me know if there are any other information that I can provide, and thank you in advance for you help and advices.
Check the input file contents. It could be a problem.
import java.io.File;
import java.util.Scanner;
public class Sample {
public static void main(String[] args) throws Exception {
String fileName = "src/main/resources/input-01.txt";
readInput(fileName);
}
public static void readInput(String fileName) throws Exception {
File file = new File(fileName);
Scanner fileInput = new Scanner(file);
//Read T
int var = fileInput.nextInt();
System.out.println("var = " + var);
}
}
input-01.txt file content
10 sampletext
output
var = 10
Process finished with exit code 0

Reading from a text file with a static constant declared

I'm trying to write a code that will read the contents of a file and I'm able to read it successfully. What I'm also trying to do is maybe declare a static constant like max_number_of_players so that the data read does not exceed this. Is there a way that I can do this? My code so far:
import java.io.*;
import java.util.*;
public class Test{
public static void main(String[] args) throws IOException
{
String fileName = "Data/players.txt";
File file = new File(fileName);
Scanner in = new Scanner(file);
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(line);
}
in.close();
}
}
Just add another condition to the while-loop:
int playerCount = 0;
while(in.hasNextLine() && playerCount++ < max_number_of_players){
...

File IO using java

I am new to java and using netbeans v8. I am trying to read strings from a file and saving modifications in a new file but when I run the code it does not show anything it continues running.
code is
package filereadingandwriting;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class FileReadingAndWriting {
public static void readAndWrite() throws Exception
{
File inputFile = new File("names.txt");
Scanner input = new Scanner(System.in);
File outFile = new File("output.txt");
PrintWriter writer = new PrintWriter(outFile);
for(int i = 0;input.hasNextLine(); i++)
{
String inputLines = input.nextLine();
writer.println("Sr#" + i + " " + inputLines);
}
input.close();
} // readAndWrite function ends.
public static void main(String[] args) throws Exception {
// TODO code application logic here
readAndWrite();
} // main function ends.
} //FileReadingAnd Writing class ends.
If you want to read from your inputFile you have to change your code to:
File inputFile = new File("names.txt");
Scanner input = new Scanner(inputFile);
In your case you would read from STDIN.
Also you should use the newer java.nio.* API
Just change new Scanner(System.in); to new Scanner(inputFile);.

Read numbers separated by ":" from file - Java

I'm having some problems reading some numbers separated by ":" from a txt file in java.
This is what i have so far:
public static void main(String []args) {
Scanner keyb = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputFile = keyb.nextLine();
System.out.print("Enter output file name: ");
String outputFile = keyb.nextLine();
File file = new File(inputFile);
try {
Scanner sc = new Scanner (file);
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} catch(FileNotFoundException e) {
System.out.println("File not found!");
}
}
File numbers.txt
12.1:15.42
0.23:0.25
-9.2:-8.1
13.5:15.9
1024:1023.9
1.0e-3:1.0e-4
15.92:-9.35
18.26:6.4
55.931:55.930
256:512
I dont understand why its not being read...any help would be much appreciated! thank you!
I tried testing your program and got correct output. Take a look
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Read {
public static void main(String[] args) {
File file = new File("numbers.txt");
try {
#SuppressWarnings("resource")
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
}
}
Output:
12.1:15.42
0.23:0.25
-9.2:-8.1
13.5:15.9
1024:1023.9
1.0e-3:1.0e-4
15.92:-9.35
18.26:6.4
55.931:55.930
256:512
I recommend using java.util.BufferedReader to read a file. There generally easy to use compared to the Scanner class.
...
BufferedReader br = new BufferedReader(new FileReader(inputFile));
String inLine; //Buffer used to store the current line
while ((inLine = br.readLine()) != null) //keep reading until we reach the end of file
{
System.out.println(inLine);
}
Tutorial: Java >> BufferedReader
Make use of the split method in the string class and equate the output to an array,each index will have a different number if they are all indeed seperated by the same character that you have specified above: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html and http://www.coderanch.com/t/385246/java/java/split-method-String-API might help but I strongly recon u download all the APIs

How to read data from a file and put it into variable and output to a different file. Java

Intro java class tard here. I'm trying to read data from a file and then manipulate to a different file and save it. I think i'm close but having issues using scanner and .IO together. Any help would be great.
import java.util.Scanner;
import java.io.*;
public class fileswitch
{
public static void main(String[] Args) throws IOException
{
String filename;
String filename2;
String text;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of a file: ");
filename = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(filename);
System.out.print("Enter the name of a second file: ");
filename2 = keyboard.nextLine();
PrintWriter outputFile2 = new PrintWriter(filename2);
while (filename.hasNextLine())
{
text = filename.readAllLines();
text = text.toUpperCase();
outputFile2.print(text);
outputFile2.close();
}
}
}
You can also use for creating a new file
package test;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class WriteStringToFile {
public static void main(String[] args) throws IOException {
String string = "This is\na test";
File file = new File("test.txt");
FileUtils.writeStringToFile(file, string);
}
}
And that is a good practice because you do not have to close streams.
This generates the test.txt file with the expected output
Try using BufferedReader
BufferedReader pw = new BufferedReader(new FileReader(fileName));
String s = null;
s = pw.readLine();
Working example
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
String filePath = keyboard.next();
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
String line = bufferedReader.readLine();
System.out.println(line);
}
Enter path on console as
C:\Users\path\Desktop\1.txt
You can use PrintWriter to write
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName2)));
Your code does not compile.
while (filename.hasNextLine()) // String#hasNextLine() does not exist
hasNextLine() belongs to Scanner which isn't being used for reading the file but just your console keystrokes from the keyboard.
If you meant to use outputFile there; that won't work either because you can't use a PrintWriter as a file reader. Well, the name kind of makes that obvious. Doesn't it?
But, you should avoid using PrintWriter for writing as well unless you're formatting the output. For plain character output prefer a FileWriter (enclosed within a BufferedWriter for performance). Similarly, for reading the files prefer a FileReader (enclosed within a BufferedReader again).
Here's how your code would look:
public static void main(String[] Args) throws IOException
{
// create the scanner for console
Scanner keyboard = new Scanner(System.in);
// read the input/output file names
System.out.print("Enter the name of a file: ");
String inFile = keyboard.nextLine();
System.out.print("Enter the name of a second file: ");
String outFile = keyboard.nextLine();
// close the scanner
keyboard.close();
// open file streams
BufferedReader reader = new BufferedReader(new FileReader(inFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
// copy the data (line by line)
String text = null;
while ((text = reader.readLine()) != null)
{
writer.write(text);
writer.newLine();
}
// close the file streams
reader.close();
writer.close();
}

Categories