readFile method does not show results at console - java

This is my question :
a method readLine that reads a line from the file specified in fileName and returns the line a String.
What I am trying to do is I read and write some info into text file using eclipse. And here are my codes :
public class FileController {
private String fileName;
public FileController(){
String fileName = "student.txt";
}
public FileController(String fileName){
this.fileName = fileName;
}
public String readLine(){
String line ="";
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line = stud.toString();
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + fileName + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return line;
}
public void writeLine(String input){
try{
FileWriter fw = new FileWriter(fileName,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
outFile.println(input);
outFile.close();
}catch(IOException exception){
System.out.println(exception);
}
}
public static void main (String [] args){
FileController fc = new FileController("student.txt");
String input = "1234567H;Gabriel;23/12/1994;56;67;87";
fc.readLine();
fc.writeLine(input);
}
This works perfectly by adding the record into the text file. However, the console there doesn't shows the result. So from what I know it's the mistake was at readLine(). When I used void it works perfectly. But the question requests me to return a String. Anybody know how to solve this?
when I do println within the while loop there's record stored in there. I guess the programme took the String file= ""; this line and return the result. So how can I take the result of line in while loop and replace with the initialization?

You are overwriting the line in while loop:
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line = stud.toString();
}
So this means that only last line will get passed to student [most likely blank line] and it might not print anything or even an exception might come. Use StringBuffer and append the string and then return that.
EDIT:
Try this.
public String readLine(){
StringBuffer line =new StringBuffer();
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line.append(stud.toString());
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + fileName + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return line.toString();
}
EDIT:
If above code also returns blank then most likely issue is Strudent "toString()" method. It might be returning blank.
EDIT:
public String readLine(){
StringBuffer line =new StringBuffer();
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line.append(stud.toString());
line.append("\n");
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + fileName + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return line.toString();
}

Related

Need to know how to copy lines of text to another file in Java for data formatting program

I would like some help with a project that I am working on. I want to create a simple program that formats data into a way that is accepting of our database. I am having trouble copying the contents of the main file to the destination file. The program creates the new destination file and it writes the "Gage ID, Date/Time, Precip_1min, Precip/Year" headers in the file but there are no data values copied to the new file. I have tried to look online for some solutions but, I have had no luck in applying these solutions. The main thing that I am concentrating on is copying each line of the main file to the new created file one-by-one then I will work from there. Any assistance is very much appreciated! Here is my code so far. P.S Cowlic105.txt is the file that has the lines of data that I want to be copied.
import java.io.*;
import java.util.Scanner;
public class MyDataFormat {
public static void main(String[] args) {
String fileName = "Cowlic105.txt";
String fileName2 = "FormDatFile.txt";
String line = null;
int x;
int gageID;
int precipYTD;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
Scanner in = new Scanner(System.in);
System.out.println("Is this the file you wish to format? " + fileName + "(0 for no, 1 for yes)");
x = in.nextInt();
if (x == 0){
System.exit(0);
}
else if (x == 1){
System.out.println("Hello there you resumed the program!!!");
System.out.println("What is the ID of the rain gage? ");
gageID = in.nextInt();
System.out.println("What is the value of precipitation YTD? ");
precipYTD = in.nextInt();
File destFile = new File("FormDatFile.txt");
if(!destFile.exists()){
try {
destFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileInputStream fis = new FileInputStream(destFile);
FileWriter writer = new FileWriter(destFile, true);
BufferedWriter write2 = new BufferedWriter(writer);
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
while((line = bufferedReader.readLine()) != null){
write2.write(line);
write2.newLine();
bufferedReader.close();
write2.close();
}
writer.write("Gage ID,Date/Time,Precip_1min,Precip/Year");
writer.write("\r\n");
writer.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
}

How to given a fixed path to eclipse

Code:
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
How could I modify this code to take a file from a fixed location?
Equivalent scanner example:
Scanner in = new Scanner(new InputStreamReader(System.in));
Scanner in = new Scanner(new FileReader("C:\\Users\\Max\\Desktop\\yes.txt"));
if you only want the whole text in one string than you can use the FileInputStream
FileInputStream inputStream = new FileInputStream("foo.txt");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
if you want to read the file line bye line use the BufferdReader in Connection with StringBuilder
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
}finally {
br.close();
}
Note:
The examples are taken from #Knubo and the whole answer and further Information can be found here
To read file using Scanner class.
Try this.
Scanner input=null;
try{
input=new Scanner(new File("your_file_path\yes.txt"));
} catch(Exception ex){
System.out.println(ex.getMessage());
}
while(input.hasNext()){
System.out.println(input.next());
}
input.close();

Cannot find symbol when using bufferwriter.readline()

I'm trying to learn java but I don't know why I'm getting there errors.What I basically want is that user will input new characters and will be written to the file as long it is not the word "stop"(program terminates at this point).
Can you guys help me?
import java.io.*;
import java.util.*;
class FileHandling{
public static void main(String args[]){
System.out.println("Enter a File name");
Scanner input = new Scanner(System.in);
String file1Name = input.next();
if(file1Name == null){
return;
}
try{
File f1 = new File(file1Name+".txt");
f1.createNewFile();
String file1NameData = "";
String content = input.next();
FileWriter fileWritter = new FileWriter(f1.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
while(!(file1NameData=bufferWritter.readLine()).equalsIgnoreCase("stop")){
bufferWritter.write(file1NameData + System.getProperty("line.separator"));
}
bufferWritter.write(file1NameData);
bufferWritter.close();
}catch(Exception e){
System.out.println("Error : " );
e.printStackTrace();
}
}
}
You are trying to read from writer which you can't. You already have scanner and using it, you could read form System input i.e. Keyboard.
Change your line like:
From
while(!(file1NameData=bufferWritter.readLine()).equalsIgnoreCase("stop")){
To
while(!(file1NameData=input.nextLine()).equalsIgnoreCase("stop")){
You are trying to read from your output, not your input
while(!input.next().equalsIgnoreCase("stop")){
bufferWritter.write(file1NameData + System.getProperty("line.separator"));
}
public static void main(String[] args) throws Exception {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File("test.txt"), true))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (line.equals("stop"))
break;
writer.write(line);
writer.newLine();
}
}
}
}

Text File error Scanner

I'm writing code which deletes a word out of a text file when the user inputs it but I cant seem to get the scanner part to work
public static void Option2Method() throws IOException
{
File inputFile = new File("wordlist.txt");
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader = new Scanner(inputFile);
Scanner writer =new Scanner(tempFile);
String currentLine;
while((currentLine = reader.nextLine()) != null)
{
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.print(currentLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}
Scanner is not meant to write files, hence does not have a write() method. You can use BufferedWriterinstead.
Example:
public static void Option2Method() throws IOException {
File inputFile = new File("wordlist.txt");
FileWriter fstream = new FileWriter("TempWordlist.txt", true);
BufferedWriter writer = new BufferedWriter(fstream);
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String trimmedLine = reader.nextLine().trim();
if (trimmedLine.equals(lineToRemove))
continue;
writer.write(trimmedLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}
Using PrintWriter:
File inputFile = new File("wordlist.txt");
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("TempWordlist.txt", true)));
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String trimmedLine = reader.nextLine().trim();
if (trimmedLine.equals(lineToRemove))
continue;
writer.print(trimmedLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
Scanner doesn't have a print method. It is used to scan a file and read data from it.
If you want to write to a file, use this or that or just google "java write to file"

BufferReader in Java

I have a problem with BufferReader and OutputStream in Java. My aim: when you insert something from a keyboard - it goes to the file. How should I correct my code?
import java.io.*;
class IntoFile {
public static void main(String[] args) throws Exception{
try {
BufferedReader sisse = new BufferedReader(new InputStreamReader(System.in));
System.out.print ("Insert something: ");
String s = sisse.readLine();
byte[] buf = new byte[1024];
OutputStream valja = new FileOutputStream(new File(args[0]));
String line = null;
while ((line = br.readLine()) != null) {
}
valja.close();
}
catch (IOException e) {
System.out.println ("I/O: " + e);
}
}
}
Thanks!
I'd use Scanner and PrintWriter
C:\Documents and Settings\glowcoder\My Documents>javac Dmitri.java
C:\Documents and Settings\glowcoder\My Documents>java Dmitri
test
woohoo
quit
C:\Documents and Settings\glowcoder\My Documents>more out.txt
test
woohoo
quit
C:\Documents and Settings\glowcoder\My Documents>
Code:
import java.io.*;
import java.util.*;
class Dmitri {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter("out.txt");
while(in.hasNextLine()) {
String line = in.nextLine();
out.println(line);
out.flush(); // not necessary every time, but simple to do so
if(line.equalsIgnoreCase("QUIT")) break;
}
out.close();
}
}
HI I am providing a sample code through which you can write in the file after user enters characters or line from keyboard.
try{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
In the our.write pass the line(variable) string argument and the string will be written in that file.

Categories