I have to take name and address of user from user and put it into textfile. I write following code:
package selfTest.nameAndAddress;
import com.intellij.codeInsight.template.postfix.templates.SoutPostfixTemplate;
import java.io.*;
import java.util.Arrays;
/**
* Created by
*/
public class Test {
public static void main(String[] args) throws IOException {
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
//creating addressbook text file
File fl=new File("E:/addressbook.txt");
fl.createNewFile();
FileReader fr=new FileReader(fl);
BufferedReader in=new BufferedReader(fr);
boolean eof=false;
int inChar=0;
String[] name=new String[2];
String[] address=new String[2];
int counter=0;
do{
FileWriter fw=new FileWriter(fl);
BufferedWriter out=new BufferedWriter(fw);
System.out.println("Enter "+(counter+1)+" students name "+" and address");
name[counter]=br.readLine();
address[counter]=br.readLine();
out.write(name[counter]);
System.out.println("Nmae: "+name[counter]+" ddress: "+address[counter]);
counter++;
}while(counter<2);
}
}
When I run the code, it takes input from user but the text file is empty. The address and name is not written into text file. How can I store the name and address into text file in the above code.
You create the BufferedWriter, but never flush or close it.
These operations are what actually write to the file
As #ManoDestra pointed out in the comments, Java supports the try-with-resources statement, which allows you to format your statements like:
try(BufferedWriter out = new BufferedWriter(new FileWriter(fl))) {
Since BufferedWriter implements the AutoCloseable interface, Java will automatically take care of cleanup of out when the try block exits
A simpler alternative to BufferedWriter is PrintStream:
PrintStream printer = new PrintStream(new File("filepath"));
System.setOut(printer);
And then you can print whatever you want to the file, e.g.
printer.println(name[counter]);
And then close it at the end:
printer.close();
Related
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).
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();
}
I created a file named 'test.txt' and then took input from the user to write the input to the file. Everything runs fine. The program doesn't show any error at all. The file is created and the program takes input from the user but when I checked the content of the file, it was empty. Can anyone figure out what is wrong with my code? The code is as follows.
package InputOutput;
import java.io.*;
public class CharacterFileReaderAndFileWriter{
private BufferedReader br = null;
private BufferedWriter bw = null;
private PrintWriter pw = new PrintWriter(System.out, true);
public File createFile() throws IOException{
File f = new File("test.txt");
return f;
}
public void writeToFile() throws IOException{
try{
bw = new BufferedWriter(new FileWriter(createFile()));
}
catch(FileNotFoundException ex){
ex.printStackTrace();
}
//take input from the console (user)
br = new BufferedReader(new InputStreamReader(System.in));
String s;
pw.println("Please enter something");
pw.println("To stop the program, enter 'stop'");
do{
s = br.readLine();
if(s.compareTo("stop")==0)
break;
s+= "\r\n";//adding an new line to the string s
bw.write(s);
}
while(s.compareTo("stop")!=0);
br.close();
bw.close();
}
public static void main(String[] args) throws IOException{
CharacterFileReaderAndFileWriter cfr = new CharacterFileReaderAndFileWriter();
cfr.writeToFile();
}
}
Most example programs show that you have to call.flush() on your BufferedWriter before the .close(). This should not be required, .close() should call .flush() automatically, but it doesn't hurt. Also you should call all the Stream/Writer objects .close() methods in reverse order as well, again correctly written classes should call .close() on all the object they wrap, but it doesn't hurt to do it anyway.
Other things that might catch you out later:
if(s.compareTo("stop")==0)
should be
if ("stop".equalsIgnoreCase(s))
it is more efficient, eliminates the possibility of a NullPointerException on s, handles any case of stop and most importantly more idiomatic Java than using .compareTo()
s+= "\r\n";//adding an new line to the string s
bw.write(s);
should be
bw.write(System.getProperty("line.separator"));
bw.write(s);
The s+= creates intermediate objects and garbage that needs to be collected. Hard coding line endings is bad as well.
You need close the outputstream.
file.close();
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I am not sure how you are supposed to read in from system input from a Java file.
I want to be able to call java myProg < file
Where file is what I want to be read in as a string and given to myProg in the main method.
Any suggestions?
You can use System.in to read from the standard input. It works just like entering it from a keyboard. The OS handles going from file to standard input.
import java.util.Scanner;
class MyProg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Printing the file passed in:");
while(sc.hasNextLine()) System.out.println(sc.nextLine());
}
}
Well, you may read System.in itself as it is a valid InputStream. Or also you can wrap it in a BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
In Java, console input is accomplished by reading from System.in. To obtain a character based
stream that is attached to the console, wrap System.in in a BufferedReader object.
BufferedReader supports a buffered input stream. Its most commonly used constructor
is shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being
created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader,
which converts bytes to characters.
To obtain an InputStreamReader object that is linked to System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for inputStream.
Putting it all together, the following line of code creates a BufferedReader that is connected
to the keyboard:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
After this statement executes, br is a character-based stream that is linked to the console
through System.in.
This is taken from the book Java- The Complete Reference by Herbert Schildt
Use System.in, it is an InputStream which just serves this purpose
You would read from System.in just like you would for keyboard input using, for example, InputStreamReader or Scanner.
You can call java myProg arg1 arg2 ... :
public static void main (String args[]) {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
}
You probably looking for something like this.
FileInputStream in = new FileInputStream("inputFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
class myFileReaderThatStarts with arguments
{
class MissingArgumentException extends Exception{
MissingArgumentException(String s)
{
super(s);
}
}
public static void main(String[] args) throws MissingArgumentException
{
//You can test args array for value
if(args.length>0)
{
// do something with args[0]
}
else
{
// default in a path
// or
throw new MissingArgumentException("You need to start this program with a path");
}
}