Reading an input text file - java

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.

Related

Java Scanner doesn't read

I am trying to download a file that contains an integer from a remote machine, increase the value of the integer locally, write the new value to the same file and upload the file. I use scp. It downloads the file successfully. I use shell file for downloading and uploading processes. But I have problems with Scanner.
Here is the code:
import java.io.*;
import java.util.*;
public class shell {
public static void main(String[] args) throws IOException{
Runtime.getRuntime().exec("/home/ayyuce/Desktop/download.sh");
File f= new File("/home/ayyuce/Desktop/yeni.txt");
PrintWriter pw = new PrintWriter(f);
Scanner s= new Scanner(f);
int num=0;
if(s.hasNextLine()){
num=s.nextInt();
} else {
System.out.println("Error");
}
int increase=num++;
pw.println(increase);
Runtime.getRuntime().exec("/home/ayyuce/Desktop/upload.sh");
s.close();
pw.close();
}
}
The output is: Error
I wonder what is the problem with Scanner.
Thank you so much!
PrintWriter pw = new PrintWriter(f);
From javadoc
file - The file to use as the destination of this writer. If the
file exists then it will be truncated to zero size; otherwise, a new
file will be created. The output will be written to the file and is
buffered.
Of course, Scanner can't read anything, because the file was truncated to zero size in new PrintWriter(f).

Read and Write with java from one file to another

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)

While loop for reading text file error java

My goal is to read a simple text file, and output it's results.
For some reason, I get an error for not being able to find the file specified, even though it's in the same folder. I'm a little stumped as to why it's not working.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
class Test
{
public static void main(String[] args)
throws IOException
{
int number;
File inputFile = new File("input.txt");
Scanner file = new Scanner(inputFile);
while(file.hasNext()) {
number = file.nextInt();
System.out.println(number);
}
System.out.println("End of file detected");
}
}
That file needs to be immediate inside your project folder. If its still not working you can use absolute path instead of relative path as alternative.
like e.g D:\\test.txt
Which folder are you talking about? If you are executing the app from Eclipse, the textfile must be in the directory where .project, .classpath, etc. files and folders are.
Here is a way to choose a file graphically using JOptionPane
ArrayList<String> lines = new ArrayList<>();
JOptionPane.showMessageDialog(null, "Please choose a file");
JFileChooser input = new JFileChooser();
int a = input.showOpenDialog(null);
String file = "";
if (a == JFileChooser.APPROVE_OPTION) {
File selectedFile = input.getSelectedFile();
file = selectedFile.getPath();
}
//use file input to read in line one at a time
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}

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);.

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