Creating, writing to and reading files - java

I know there are many questions related to this, but I still do not follow. I have copied the below code from a tutorial on how to create, write to and read from a file. There is a CreateFile class, a ReadFile class and a Demo class:
CreateFile.java
import java.io.*;
import java.lang.*;
import java.util.*;
public class CreateFile {
private Formatter x;
public void openFile(){
try{
x = new Formatter("chinese.txt");
}
catch(Exception e)
{
System.out.println("You have an error");
}
}
public void addRecords(){
x .format("%s%s%s", "20 ", "bucky ", "robers");
}
public void closeFile(){
x.close();
}
}
ReadFile.java
public class ReadFile {
private Scanner x;
public void openFile()
{
try{
x = new Scanner(new File("words.txt"));
}
catch(Exception e){
System.out.println("could not find file");
}
}
public void readFile()
{
while(x.hasNext())
{
String a = x.next();
String b = x.next();
String c = x.next();
System.out.printf("%s %s %s\n", a,b,c);
}
}
public void closeFile()
{
x.close();
}
}
public class Demo {
public static void main(String[] args) {
CreateFile g = new CreateFile();
g.openFile();
g.addRecords();
g.closeFile();
WordCounter r = new WordCounter();
r.openFile();
r.readFile();
r.closeFile();
}
In Demo.java if I remove the last four statements related to reading the file, the first four statements related to opening and writing to a file run without error. However, once I add
WordCounter r = new WordCounter();
r.openFile();
r.readFile();
r.closeFile();
and run the program, it outputs: Exception in thread "main" could not find file. I am not sure what is going on, is the file chinese.txt never being created?

I'd suggest that you look into serialization it much easier and simpler than writing to .txt files.
But if you really need to do .txt files this is how you write to a .txt file
//This gets your project directory
private String projectPath = System.getProperty("user.dir");
//call save()
String save("test.txt", "This is will be save to a test.txt file");
private boolean save(String textfile String outputtext){
String filepath = projectPath + textfile;
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(filepath));
writer.write(outputtext);
writer.close();
} catch(IOException e) { }
return true;
}
And this is how you read it
private String load(String textfile){
String temp="";
String filepath = projectPath + textfile;
try{
BufferedReader reader =new BufferedReader(new FileReader(filepath));
while(true){
//this will read one line at a time you can append it output
try {
temp+= reader.readLine();
//If no more lines break out of the loop
if(line==null)
break;
}catch(IOException e){}
}
reader.close();
}
catch(IOException e){}
//Return contents of the file you loaded
return temp;
}
I hope that this code is clear enough. If you have any further questions let me know. I'll gladly answer them.

Related

Printing a string to a file in all uppercase, lowercase and reverse java

I need to input a line of text into the code and have it print that text to the file in all upper came, all lower case, and reverse. I know how to do this with string, but cannot figure out how to get it to print to the file this way. I do not need help with getting the text to print in the output but getting it to print all these ways to the actual PrintToFile.txt without actually inputting it all those different ways.
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class PrintToFile { //open class
private static Formatter output;
public static void main (String args[]) throws IOException { //open main
openFile();
addRecords();
closeFile();
BufferedReader printFile = new BufferedReader(new FileReader("YoastReginaITM251Project9.txt"));
for (String line; (line = printFile.readLine()) != null;) { //open for
System.out.println("Text: " + line);
System.out.println("Text in Upper Case: " + line.toUpperCase());
System.out.println("Text in Lower Case: " + line.toLowerCase());
System.out.println("Text in Reverse Case: " + line);
} //close for
} //close main
public static void openFile() { //open openFile
try { //open try
output = new Formatter("PrintToFile.txt"); //open file
} //close try
catch (SecurityException securityException) { //open catch
System.err.println("Write permission denied. Terminating.");
System.exit(1);
} //close catch
catch (FileNotFoundException fileNotFoundException) { //open catch
System.err.println("Error opening file. Terminating.");
System.exit(1);
} //close catch
} //close openFile
public static void addRecords() { //open addRecords
try { //open try
output.format("%s", input.nextLine());
} //close try
catch (FormatterClosedException formatterClosedException) { //open catch
System.err.println("Error writing to file. Terminating.");
} //close catch
catch (NoSuchElementException elementExpcetion) { //open catch
System.err.println("Invalid input. Please try again.");
input.nextLine();
} //close catch
} //close AddRecords
public static void closeFile() { //open closeFile
if (output != null)
output.close();
} //close closeFile
} //close class
String input = "MagicString";
String upperCase = input.toUpperCase();
String lowerCase = input.toLowerCase();
StringBuilder sb = new StringBuilder();
sb.append(input);
String reversedString = sb.reverse().toString();
You can use the StringBuilder class (https://docs.oracle.com/javase/tutorial/java/data/buffers.html) to create new strings as you like, then print those to file.
The simple way is:
Read from a file into a string.
Apply toUpperCase() and store it into another string.
Apply toLowerCase() and store it into another string.
Apply reverse()[own created method] and store it into another string.
Then write all these strings into the destination file.
Here is the code by which you can perform the required operation.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class FileRW {
public static void main(String[] args) throws FileNotFoundException, IOException {
String filename="filename.txt";
String upper,lower,reverse,line;
upper=null;
lower=null;
reverse=null;
line=null;
FileReader fileReader=new FileReader(filename);
BufferedReader bufferedReader=new BufferedReader(fileReader);
while((line=bufferedReader.readLine())!=null)
{
upper=line.toUpperCase();
lower=line.toLowerCase();
reverse=reverse(line);
writeToFile(upper,lower,reverse);
}
}
static String reverse(String test)
{ String returnString="";
int len=test.length();
for(int i=len-1;i>=0;i--)
{
returnString+=test.charAt(i);
}
return returnString;
}
static void writeToFile(String line1,String line2,String line3) throws IOException
{
String filename="content.txt";
File file =new File(filename);
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(line1);
bufferWritter.write(line3);
bufferWritter.write(line2);
bufferWritter.close();
System.out.println("Done");
}
}
Maybe you could use the Scanner and FileWriter classes as well. You can try something like this if it works for your purposes:
import java.io.*;
import java.util.*;
public class Solution{
/*
* Print a string to the output file
*/
private void print(String s, FileWriter o) {
try {
o.write(s + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* Convert the strings to uppercase,
* lowercase and reverse.
*/
private void solver(Scanner sc, FileWriter o){
while(sc.hasNextLine()) {
String s = sc.nextLine();
print(s.toUpperCase(), o);
print(s.toLowerCase(), o);
print(new StringBuilder(s).reverse().toString(), o);
}
}
/*
* Main method
*/
public static void main(String args[]){
File inFile = new File("input.txt");
File outFile = new File("output.txt");
try{
Scanner sc = new Scanner(inFile);
FileWriter o = new FileWriter(outFile);
Solution s = new Solution();
s.solver(sc, o);
sc.close();
o.close();
} catch(Exception e){
System.out.println(e);
}
}
}

Reading a .txt file that results in a stackoverflow error

Can someone please help me determine what I am doing wrong with my code. I am getting a stackoverflow error. At the end of my code I am using recursion and I don't have a base case to stop the program. It keeps looping and displaying my text file until I get a stackoverflow error.
public class Reader
{
public static String readFinalQuestionBank() throws Exception
{
File textFile = new File("C:\\Users\\Joseph\\Documents\\School Files - NHCC\\CSci 2002\\FinalQuestionBank_JosephKraemer.txt"); //file location
try
{
Scanner scan = new Scanner(textFile); //Scanner to import file
while(scan.hasNextLine()) //Iterator - while file has next line
{
String qBank = scan.nextLine(); //Iterator next line
String[] tempArray = qBank.split("::"); //split data via double colon
System.out.println(qBank); //print data line
}
scan.close(); //close scanner
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return readFinalQuestionBank(); //use of Recursion
}//end method readFinalQuestionBank
}//end class Reader
if your main objective is to read the whole input file by implementing recursivity take a look at the following example, it replaces the while statement with a recursive method call.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Reader
{
public static String readFinalQuestionBank() throws Exception
{
File textFile = new File("C:\\Users\\Diego\\Documents\\sandbox\\input.txt");
String output = "";
try
{
Scanner scan = new Scanner(textFile);
output = readLineRecursively(scan);
scan.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return output;
}
private static String readLineRecursively(Scanner scan){
if(!scan.hasNextLine()){
return "";
}
String qBank = scan.nextLine();
return qBank + "\n" + readLineRecursively(scan);
}
public static void main(String[] args){
try {
System.out.println(readFinalQuestionBank());
} catch (Exception e) {
e.printStackTrace();
}
}
}

reading in a file from computer and editing it and saving as a new file

I am trying to load in a file from my computer with all the words of the dictionary in the file.
When I load the file i put the words into an array of strings.
I then want to eliminate all words that have more than 9 letters in them.
I then want to save the words that are 9 letters or smaller into another separate text file.
When i try to open the new file it only has 9 words in it, yet my print to the screen on eclipse will print the all words of nine or less letters.
Can anyone help!
This is a program that was gave to me as part of the question.
import java.io.*;
public class FileIO{
public String[] load(String file) {
File aFile = new File(file);
StringBuffer contents = new StringBuffer();
BufferedReader input = null;
try {
input = new BufferedReader( new FileReader(aFile) );
String line = null;
int i = 0;
while (( line = input.readLine()) != null){
contents.append(line);
i++;
contents.append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException ex) {
System.out.println("Can't find the file - are you sure the file is in this location: "+file);
ex.printStackTrace();
}
catch (IOException ex){
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
finally {
try {
if (input!= null) {
input.close();
}
}
catch (IOException ex) {
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
}
String[] array = contents.toString().split("\n");
for(String s: array){
s.trim();
}
return array;
}
public void save(String file, String[] array) throws FileNotFoundException, IOException {
File aFile = new File(file);
Writer output = null;
try {
output = new BufferedWriter( new FileWriter(aFile) );
for(int i=0;i<array.length;i++){
output.write( array[i] );
output.write(System.getProperty("line.separator"));
}
}
finally {
if (output != null) output.close();
}
}
}
this is the class i tried to use
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
public class countdown{
public static void main(String args[]){
FileIO reader = new FileIO();
Scanner scan = new Scanner(System.in);
String[] inputs = reader.load("C:/Users/Sony/Documents/dict.csv"); //Reading the File as a String array from a file called dict
String[] input = new String[inputs.length]; //new String array for strings less than 9 letters
for(int i=0;i<inputs.length;i++){
if(inputs[i].length()<=9) { //if string of index i is less than 9
input[i]=inputs[i]; //add it to the new array called input
System.out.println(input[i]); //print line to check
}
}
try{
reader.save("C:/Users/Sony/Documents/dictnew.csv",input);
//this is where i save it to the new file called dictnew.
}catch (Exception e){
System.out.println(e.getClass());
}
}
}
After reading how you want you can split rest logic remains same.
package com.srijan.playground;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FilterLengthWords {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("Sample.txt"));
bw = new BufferedWriter(new FileWriter("Output.txt"));
String tmp = null;
while((tmp=br.readLine())!=null) {
if(tmp.length()<=9) {
bw.write(tmp);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br!=null) {
br.close();
br=null;
}
if(bw!=null){
bw.close();
bw=null;
}
}
}
}
Thanks

Java: Make a void-method out of this class (textfile changer)

What I want to do: My class copytest reads a textfile, edits one character and save this new file in a new directory. I want to program a void-method out of it, which does exactly the same and can then be used the following way:
copy(String "C:\\Old.txt", String "C:\\New.txt", int 1, int 1)
Now copy does exactly the same as my old class copytest, it reads the old file, edits it and saves it.
My first idea was to have two files as the first to arguments, but this is obviously impossible. My new idea is to give the method two strings of the wanted directories of the old and the new file. It still doesn't work. I hope, you understand, what I want to do and how to solve this problem.
Old class code (works):
import java.io.*;
import java.util.Scanner;
public class copytest {
public static void main(String[] args) throws Exception {
readFile();
}
public static void readFile() throws Exception {
// Location of file to read
File file = new File("...old.txt");
Scanner scanner = new Scanner(file);
int lineNumber=1;
int charNumber=1;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
writeFile(line);
i++;
}
scanner.close();
System.out.println("File copied.");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File("...new.txt");
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
}
New void code (first try with file as argument):
public void copy(file old, file new, int x, int y) {
public static void readFile() throws Exception {
Scanner scanner = new Scanner(old);
int lineNumber=y;
int charNumber=x;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
writeFile(line);
i++;
}
scanner.close();
System.out.println("File copied.");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File(new.getPath());
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
readFile();
}
New try with strings as argument, but still doesn't work:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class copytestnew {
public void copy(String old, String newone, int x, int y) {
// Location of file to read
File file = new File(old);
Scanner scanner = new Scanner(file);
int lineNumber=y;
int charNumber=x;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file2 = new File(newone);
output = new BufferedWriter(new FileWriter(file2, true));
output.write(line);
output.write(newLine);
output.close();
i++;
}
scanner.close();
System.out.println("File copied");
}
}
I remember you! I answeared you last time on how to replace the char at one of the lines.
First, change the decleration to
public static void copy(String old, String newone, int x, int y) throws IOException {
NOTICE the throws statment!
And now when you want to call this method you should use it inside a try-catch block or declear that you throwing exception same as you did at the copy function.
public void copy(file old, file new, int x, int y) {
public static void readFile() throws Exception {
You're defining a function inside a method. As all functions in java are methods (static or non-static), this is not permitted. Try this:
class IDontKnowHowToNameIt {
public static void copy(file old, file new, int x, int y) {
//...
// call readFile from here
// ...
}
private static void readFile() throws Exception {
//...
}
}

Is there a way to make this Java program more interactive?

I have written the following very simple Java program to ask user enter a file name, then it will report the number of lines of this file to the standard output:
import java.io.*;
import java.util.*;
public class CountLine {
public static void main(String[] args)
{
// prompt the user to enter their file name
System.out.print("Please enter your file name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
fileName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the file name, " + fileName);
File file = new File("C:/Users/Will/Desktop/"+fileName);
Scanner scanner;
try {
scanner = new Scanner(file);
int count =0;
String currentLine;
while(scanner.hasNextLine())
{
currentLine=scanner.nextLine();
count++;
}
System.out.println("The number of lines in this file is "+count);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("There is no such file");
e.printStackTrace();
}
}
}
It is working.I would be really thankful if experts could help me
see if there is anything that can be improved in this code fragment,
If the file is not found, the exception is caught in the outermost catch statement and print out the stack trace. However, I think it is not very user-friendly, is there a way if the file does not exist, then the whole process restarts from beginning?
Thanks in advance.
Get some Structure in your code:
public static void main(String[] args)
{
string output;
string fname = readFileName();
if (fileValid(fname)) //Ensure FileExists
{
int lineCount = scaneFile(fname);
output = "some output text including line numbers"
}
else
{
output = "File Not Valid..."
}
//showOutput...
}
Obvious change is to make a method countLines(String filename) that contains most of the code currently in main(). Obviously main() will call countLines().
Prompting for a file could live in main() or another method.
To restart on error you need a loop like:
filename = // read filename from stdin;
while(keepGoing(filename)) { // null check or whatever to let you out of the loop
try {
int numLines = countLines(filename);
println("num lines in " + filename + "=" +numLines);
}
catch(Exception ex) { // or just specific excpetions
ex.printStackTrace();
}
}
Unless you want to make a GUI. I suggest you receive the path to the file as a command line parameter.
If file doesn't exist print a message and exit. That's all.
The command line will give the user the option to move up with the up-key, edit the name and run again.
This class is named LineCounter and is the "business logic"
package countlines;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
private int lineCount = 0;
public LineCounter(File file) throws IOException{
BufferedReader inFile = new BufferedReader(new FileReader(file));
while(inFile.readLine() != null) {
lineCount++;
}
inFile.close();
}
public int getLineCount() {
return lineCount;
}
}
This class is the "presentation logic"
package countlines;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main (String[] args){
if (args.length != 1){
System.out.println("Usage: java countlines/Main filePath");
System.exit(1);
}
File f = new File(args[0]);
if (!f.exists()){
System.out.println("File "+f.getAbsolutePath()+" doesn't exist");
System.exit(2);
}
if (f.isDirectory()){
System.out.println(f.getAbsolutePath()+" is a directory");
System.exit(2);
}
LineCounter c;
try {
c = new LineCounter(f);
System.out.println(c.getLineCount());
} catch (IOException e) {
System.out.println("Error reading file " + f.getAbsolutePath());
}
}
}

Categories

Resources