Input and Output program - java

I am trying to get this program to read an input file line by line and then print it to an output file, so for example:
Input file contains:
cookies
cake
ice cream
I want the output file to display this:
Line 1: cookies
Line 2: cake
Line 3: ice cream
I cannot figure out how to do this however, so any help will be appreciated.
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.print("Enter the input file: ");
String name = in.next();
FileReader file = new FileReader(name);
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
while(line != null){
text += line;
line = reader.readLine();
}
reader.close();
System.out.print("Enter the output file: ");
String out = in.next();
FileWriter filew = new FileWriter(out);
BufferedWriter buffw = new BufferedWriter(filew);
buffw.write(text);
buffw.close();
System.out.print("File written!");
in.close();
}
}

The problem is with the loop like:
while(line != null){
text += line;
line = reader.readLine();
}
readLine method would eat up the new line character and hence you don't see it in the output file. You need to append a new line character at the end like:
while(line != null){
text += line;
text += '\n';
line = reader.readLine();
}
I would suggest you using StringBuilder instead of string concatenation like:
StringBuilder stringBuilder = ...
while ..
stringBuilder.append(line);
stringBuilder.append('\n');
...

You have to add the end of line character again, because readLine() removes it:
while(line != null){
text += line;
text +="\n";
line = reader.readLine();
}

Related

Cannot Read Next Console Line - NoSuchElementException

The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places
however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable
This is Current Method
private static void FileWritting () throws IOException {
System.out.println("\n6.7.2 Writting Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner2 = new Scanner(System.in);
String filename = Scanner2.nextLine();
FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
BufferedWriter bw = new BufferedWriter(writehandle);
int n = 10;
for(int i=1;i<n;++i)
{
double value = Math.sqrt(i);
String formattedString = String.format("%."+ (i-1) +"f", value);
System.out.println(formattedString);
// bw.write(line);
bw.newLine();
}
bw.close();
writehandle.close();
Scanner2.close();
}
Where This is the previous method
System.out.println("6.7.1 Reading Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner1 = new Scanner(System.in);
String filename = Scanner1.nextLine();
FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
BufferedReader br = new BufferedReader(readhandle);
String line = br.readLine ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println("The number of words is: " + count);
br.close();
Scanner1.close();
}
You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).
More info and a better explanation

Formatting string to get just words in a column

I have a text:
c:\MyMP3s\4 Non Blondes\Bigger!\Faster, More!_Train.mp3
I want to remove form this text these characters: :,\!._
And format the text then like this:
c
MyMP3s
4
Non
Blindes
Bigger
Faster
More
Train
mp3
And write all of this in a file.
Here is what I did:
public static void formatText() throws IOException{
Writer writer = null;
BufferedReader br = new BufferedReader(new FileReader(new File("File.txt")));
String line = "";
while(br.readLine()!=null){
System.out.println("Into the loop");
line = br.readLine();
line = line.replaceAll(":", " ");
line = line.replaceAll(".", " ");
line = line.replaceAll("_", " ");
line = System.lineSeparator();
System.out.println(line);
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Write.txt")));
writer.write(line);
}
And it doesn't work!
The exception:
Into the loop
Exception in thread "main" java.lang.NullPointerException
at Application.formatText(Application.java:25)
at Application.main(Application.java:41)
At the end of your code, you have:
line = System.lineSeperator()
This resets your replacements. Another thing to note is String#replaceAll takes in a regex for the first parameter. So you have to escape any sequences, such as .
String line = "c:\\MyMP3s\\4 Non Blondes\\Bigger!\\Faster, More!_Train.mp3";
System.out.println("Into the loop");
line = line.replaceAll(":\\\\", " ");
line = line.replaceAll("\\.", " ");
line = line.replaceAll("_", " ");
line = line.replaceAll("\\\\", " ");
line = line.replaceAll(" ", System.lineSeparator());
System.out.println(line);
The output is:
Into the loop
c
MyMP3s
4
Non
Blondes
Bigger!
Faster,
More!
Train
mp3

edit line in a text file

i've tried this code that i found in the internet
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\n";
}
reader.close();
// replace a word in a file
//String newtext = oldtext.replaceAll("drink", "Love");
//To replace a line in a file
String replace = JOptionPane.showInputDialog("Enter what to replace: ");
String toreplace = JOptionPane.showInputDialog("Enter where to replace: ");
String newtext = oldtext.replaceAll(replace, toreplace);
FileWriter writer = new FileWriter("file.txt");
writer.append(newtext);writer.close();
but mine won't output like this code will do. the output of this code is like this:
unedit:
jojo moyes
kim possible
dexter laboratory
edited: when i enter "mary" to edit "kim"
jojo moyes
mary possible
dexter laboratoty
but mine will be like this
jojo moyes
kim possible
dexter laboratoy
mary possible
mine tho had register before editing. and in the register there is also time that it will store something in the text file. and there goes the edit function if the user wants to edit something in the information that he entered (you get the picture)
EDITED: here's my code
public void Register_Edit_Info() throws IOException{
FileWriter writeFile=new FileWriter("voters.txt", true);
BufferedWriter outFile=new BufferedWriter(writeFile);
File readFile=new File("voters.txt");
BufferedReader read=new BufferedReader(new FileReader(readFile));
String choice2;
String [] secondMenu = {"Register", "Edit", "Delete", "Back"};
do{
choice2=(String)JOptionPane.showInputDialog(null, "Please choose:", "Election 2765", 1, null, secondMenu, secondMenu[0]);
switch(choice2){
case "Register":
String [] menuGender={"Male", "Female"};
String [] menuStatus={"Single", "Married", "Widow(er)", "Legally separated"};
do{
age=Integer.parseInt(JOptionPane.showInputDialog("Age: "));
while(age<18){
JOptionPane.showMessageDialog(null, "Voter should be 18 or above");
age=Integer.parseInt(JOptionPane.showInputDialog("Age: "));
}
name=JOptionPane.showInputDialog("Full Name: ");
gender=(String)JOptionPane.showInputDialog(null, "Gender:", "Election 2765", 1, null, menuGender, menuGender[0]);
if(gender=="Male"){
gender="Male";
}
else{
gender="Female";
}
dBirth=JOptionPane.showInputDialog("Date of Birth: ");
pBirth=JOptionPane.showInputDialog("Place of Birth: ");
address=JOptionPane.showInputDialog("Address\n(Province, City/Municipality, Barangay, House No./Street: ");
status=(String)JOptionPane.showInputDialog(null, "Civil Status:", "Election 2765", 1, null, menuStatus, menuStatus[0]);
if(status=="Single"){
status="Single";
}
else if(status=="Married"){
spouse=JOptionPane.showInputDialog("Spouse Name: ");
status="Married(Spouse: "+spouse+")";
}
else if(status=="Widow(er)"){
status="Widow(er)";
}
else{
status="Legally Separated";
}
citizenship=JOptionPane.showInputDialog("Citizenship:");
job=JOptionPane.showInputDialog("Profession/Occupation: ");
tin=JOptionPane.showInputDialog("Tin Number: ");
father=JOptionPane.showInputDialog("Father's Full Name: ");
mother=JOptionPane.showInputDialog("Mother's Full Name: ");
votersNumber++;
vNumber=Integer.toString(votersNumber);
outFile.append(vNumber+"/"+name+"/"+age+"/"+gender+"/"+dBirth+"/"+pBirth+"/"+address+"/"+status+"/"+citizenship+"/"+job+"/"+father+"/"+mother);
outFile.newLine();
selectYN=JOptionPane.showInputDialog("You are now registered. Do you want to register more?\n[1]Yes [2]No");
}while(!"2".equals(selectYN));
break;
case "Edit":
vNumForEdit=JOptionPane.showInputDialog("Enter voters number: ");
String line=null, oldtext="";
while((line=read.readLine())!=null){
oldtext+=line+"\n";
String [] info=line.split("/");
if(info[0].matches(vNumForEdit)){
String [] forEditMenu={"Name", "Age", "Gender", "Date of Birth", "Place of Birth", "Address", "Civil Status", "Citizenship", "Profession/Occupation", "Father's Name", "Mother's Name"};
forEdit=(String)JOptionPane.showInputDialog(null, line+"\n\nPlease select what you want to edit", "National Election 2765", 1, null, forEditMenu, forEditMenu[0]);
switch(forEdit){
case "Name":
oldName=JOptionPane.showInputDialog("Enter old name: ");
newName=JOptionPane.showInputDialog("Enter new name: ");
String newText = oldtext.replaceAll(oldName, newName);
outFile.append(newText);
break;
}
}
}
case "Delete":
break;
}
}while(choice2!="Back");
read.close();
outFile.close();
}
This Answer is for the first portion of your question.(before edit).
public static void main(String[] args) throws FileNotFoundException,IOException {
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\n";
}
reader.close();
System.out.println(oldtext);
// replace a word in a file
//String newtext = oldtext.replaceAll("drink", "Love");
//To replace a line in a file
String replace = JOptionPane.showInputDialog("Enter what to replace: ");
String toreplace = JOptionPane.showInputDialog("Enter where to replace: ");
String newtext = oldtext.replaceAll(replace, toreplace);
System.out.println(newtext);
java.io.FileWriter writer = new java.io.FileWriter("file1.txt");
writer.write(newtext);
writer.close();
}
When first prompt open I write "kim" and where to replace , I write "marry" and the output like this. I think your code is fine except not to use append() for FileWriter. you should use write() method for FileWriter.
EDIT:
Use different file name (I don't know about if reading and writing operation occur for same file.) for FileWriter and for initialization you can use
FileWriter writeFile=new FileWriter("voters1.txt");
And let me know if the problems is solved.

Reading from file. Android, Java

I have some problem with reading file with Scanner.
My file has a following format:
line 1(basic signs, f.e.: ##%%&&).
line 2(number of lines with data, f.e.: 70)
line 3(some info)
line 4-74(some data in any format with semiColon as a delimiter)
I need to implement loop which started from fourth line and allows me to fill my ListView.
How to solve this problem?
here is part of code:
Scanner read = null;
Pattern b = Pattern.compile(";|\\|\n ");
String BasicSign, NumberOfFields, barcode, name, type, amount, price;
try {
Log.d(LOG_TAG1, "--- Reading from spr: ---");
File file = Environment.getExternalStorageDirectory();
File textFile = new File(file.getAbsolutePath() + File.separator + "myFile1.spr");
read = new Scanner(textFile);
read.useDelimiter(b);
while (read.hasNext()) {
BasicSign = read.next();
NumberOfFields = read.next();
barcode = read.next();
name = read.next();
amount = read.next();
price = read.next();
tvBarcode.setText(barcode123);
tvMyName.setText(name);
tvType.setText(type);
tvPrice.setText(price);
}
read.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You could process your textfile linewise and skip the first 3 lines and start in the 4th. This is a simple straight forward solution:
BufferedReader br = new BufferedReader(textfile);
br.readLine(); // skip line
br.readLine(); // skip line
br.readLine(); // skip line
String line = br.readLine(); // start in 4th line
while (line !=null) { // end of file not reached
Scanner read = new Scanner(line);
read.useDelimiter(b);
//your while loop and processing
line = br.readLine(); // read line for next iteration
}
br.close();

Line by line input via java console

Please help me to input by line by line via java console. Now i can give input only as one line. How to give multiple inputs in line by line??
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
String CurLine = ""; // Line read from standard in
while (!(CurLine.equals("quit"))){
CurLine = in.readLine();
if (!(CurLine.equals("quit"))){
System.out.println("You typed: " + CurLine);
}
}
You need to use Scanner and loop through to ask for multiple times.
For example
Scanner stdin = new Scanner(new BufferedInputStream(System.in));
while (stdin.hasNext()) {
//Get input and do your logic.
}
I'm not sure I understand your question but...
final List<String> inputs = new ArrayList<String>();
final Scanner in = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.print("> ");
inputs.add(in.next());
}
System.out.println(inputs);
Use the new Console class:
Console console = System.console();
if (console != null) {
Scanner scanner = new Scanner(console.reader());
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// Do something with your line
}
}
End the input by pressing ^Z (control-Z) followed by ENTER.
It has one caveat and that is that the console can be null inside an IDE. Try it from the command-line and you should be fine:
java path.to.my.MainClass

Categories

Resources