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);.
Related
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
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.
How do I read the following information from a txt file and write just the numbers to another text file using Java? I have it displaying to the console but it will not write to the file also.
Jones 369218658389641
Smith 6011781008881301
Wayne 5551066751345482
Wines 4809134775860430
Biggie 9925689541232325
Luke 7586425896325410
Brandy 4388576018410707
Ryan 2458912425860439
import java.util.Scanner;
import java.io.File;
public class test {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("accounts.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Read data from a file
while (input.hasNext()) {
String accountName = input.next();
Long cardNumber = input.nextLong();
//this is where I want to write just the numbers to a file called cardnums.txt
file = new java.io.File("cardnums.txt");
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.println(cardNumber);
System.out.println(cardNumber);
}
// Close the file
input.close();
}
}
I got it now.
import java.util.Scanner;
import java.io.File;
public class test {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("accounts.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Read data from a file
file = new java.io.File("cardnums.txt");
java.io.PrintWriter output = new java.io.PrintWriter(file);
while (input.hasNext()) {
String accountName = input.next();
Long cardNumber = input.nextLong();
//this is where I want to write just the numbers to a file called credit.txt
output.println(cardNumber);
System.out.println(cardNumber);
}
// Close the file
input.close();
output.flush();
output.close();
}
}
java.io.PrintWriter output = new java.io.PrintWriter(file);
First of all why are you everytime calling this in loop with same filename?
Secondly, once you define it outside loop,
Call flush() on outputstream object and close if not null (preferabbly in finally block) after loop.
if(output!=null) {
output.flush();
output.close();
}
Here's a 1-liner:
Files.write(Paths.get("cardnums.txt"), () ->
Files.lines(Paths.get("accounts.txt"))
.map(s -> s.replaceAll("\\D", ""))
.collect(toList())
.iterator());
Disclaimer: Code may not compile or work as it was thumbed in on my phone (but there's a reasonable chance it will work)
So i am working on a code that receives 2 strings. The string are "input#.txt" or "output#.txt" the # symbol is replaced with whatever number file is used. Now in the input file is the information I need to get to. How do I determine if that input.txt file can be opened and how do I open it.
I've tried a buffered reader and trying to just make the string a file.
import java.util.*;
import java.io.*;
public class Robot {
public static void readInstructions(String inputFileName, String outputFileName) throws InvalidRobotInstructionException{
try{
BufferedReader input = new BufferedReader(new FileReader(inputFileName));
File inner = new File(inputFileName);
Scanner in = new Scanner(input);
PrintWriter wrt;
wrt = new PrintWriter(outputFileName);
if(input.readLine() == null){
System.out.println("Input file not found.");
return;
}
This will read a file in:
Scanner input = new Scanner(new File("input5.txt"));
Don't forget to add throws FileNotFoundException in your main method
edit: I see you added code.
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();
}