cannot create a txt file - java

import java.util.Scanner;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class Exercise4
{
String name = null;
public String nameInitials(String sentence)
{
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(new FileOutputStream("abc.txt."));
outputStream.println(sentence);
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
System.exit(0);
}
outputStream.close();
Scanner inputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("abc.txt."));
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
System.exit(0);
}
do
{
String word = inputStream.next();
char initial = word.charAt(0);
name = initial+"."+name;
} while (inputStream.hasNext());
return name;
}
public void main(String[]args)
{
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials);
}
}
Write a method called nameInitials that takes one String as argument, pertaining to somebody's full name and returns a String of the name's initials. Usage example,
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials); //should print B.A.W.R.
I try to store the full name to a txt file and read the file. But I don't know why I cannot create the abc.txt file in the folder.

This can fix your error, I tested it
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class Exercise4
{
static String name = null;
public static String nameInitials(String sentence) {
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(new FileOutputStream("C:\\temp\\abc.txt"));
outputStream.println(sentence);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
outputStream.close();
Scanner inputStream = null;
try {
inputStream = new Scanner(new FileInputStream("C:\\temp\\abc.txt"));
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
do {
String word = inputStream.next();
char initial = word.charAt(0);
name = initial + "." + name;
} while (inputStream.hasNext());
return name;
}
public static void main(String[] args) {
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials);
}
}
the path of file not should end of .txt. just .txt

Your code is perfect it is creating the file "abc.txt." at the project level If you want to create a file named abc.txt then you must change;
new FileOutputStream("abc.txt.") to new FileOutputStream("abc.txt")
and
new FileInputStream("abc.txt.") to new FileInputStream("abc.txt")
And if you want to create the file in a particular directory then provide the full path of that directory with the file name you want to create.
for ubuntu system;
new FileOutputStream("/home/java/abc.txt")
&
new FileInputStream("/home/java/abc.txt")
and for windows system;
new FileOutputStream("C:/java/abc.txt")
&
new FileInputStream("C:/java/abc.txt")

Related

copy contents from one file to another file(dont overwrite if exists)

I have written a java code to copy contents from 1 file to other. here what it is said is that if the file exists it shoudn't be over written. i have used that case so if it exists it doesn't overwrite but it erases the entire content of the second file... kindly help me with the code. i have shared the question and the code here. kindly help!!
QUESTION:
java program which take source file and destination file as input as command line arguments. It copies the source file contents to destination file. If source file does not exist, it should give appropriate message to use. If destination file does not exist, it should be created. If it exists, program should ask that, “whether you want to overwrite?(Yes/No”.
On the basis of user choice, appropriate action should be taken.
JAVA CODE:
package com.files.file_handle;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileCopy {
public static void main(String[] args) throws IOException {
Scanner s=new Scanner(System.in);
FileReader fr = null;
FileWriter fw = null;
try {
System.out.println("enter a source file which exists");
String file1=s.next();
fr = new FileReader(file1);
System.out.println("enter a destination file");
String file2=s.next();
File f2=new File(file2);
if(!f2.exists()) {
fw = new FileWriter(file2);
f2.createNewFile();
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
System.out.println("file copied successfully");
} else {
fw = new FileWriter(file2);
System.out.println("do you want to overwrite? enter 'yes' or 'no'...");
char ans = s.next().charAt(0);
if(ans=='N'||ans=='n') {
System.out.println("couldnot enter data");
} else {
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
System.out.println("file updated successfully");
}
}
} catch(IOException e) {
System.out.println("file coudn't be found");
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) { //... }
}
}
The following code works perfectly, The issue was when open the file in write mode its content will be automatically cleared.
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileCopy {
public static void main(String[] args) throws IOException {
Scanner s=new Scanner(System.in);
FileReader fr = null;
FileWriter fw = null;
try {
System.out.println("enter a source file which exists");
String file1=s.next();
fr = new FileReader(file1);
System.out.println("enter a destination file");
String file2=s.next();
File f2=new File(file2);
if(!f2.exists()) {
fw = new FileWriter(file2);
f2.createNewFile();
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
fr.close();
System.out.println("file copied successfully");
} else {
System.out.println("do you want to overwrite? enter 'yes' or 'no'...");
char ans = s.next().charAt(0);
if(ans=='N'||ans=='n') {
fr.close();
// fw.close();
System.out.println("couldnot enter data");
} else {
fw = new FileWriter(file2);
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
fr.close();
System.out.println("file updated successfully");
}
}
} catch(IOException e) {
System.out.println("file coudn't be found");
} finally {
close(fr);
close(fw);
//fw.close();
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) { //...
e.printStackTrace();
}
}
}

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

using Java arraylist for storing data from scan from file

I am new to java, but not coding. I am trying to figure out java because it's part of my class this term and I am having a really hard problem grasping the idea of it and implementing things in java.
my problem Is that I am not sure if I am correctly using the arraylist to grab data from the scan of the file and input it into a arraylist to sort and print at a later time. I am just having issues picking up on java any help would be great since I am new to java.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.*;
public class MissionCount
{
private static ArrayList<String> list = new ArrayList<String>();
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName) throws Exception {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
inputStream = null;
throw new Exception("unable to open the file -- " + e.getMessage());
}
return inputStream;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("USage: MissionCount <datafile>");
//System.exit(1);
}
try {
System.out.printf("CS261 - MissionCount - Chad Dreher%n%n");
int crewcount = 0;
int misscount = 0;
InputStream log = getFileInputStream(args[0]);
Scanner sc = new Scanner(log);
sc.useDelimiter(Pattern.compile(",|\n"));
while (sc.hasNext()) {
String crewMember = sc.next();
list.add(crewMember);
String mission = sc.next();
list.add(mission);
}
sc.close();
// Add code to print the report here
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
InputStream log = getFileInputStream(args[0]);
Change that line to as follows :-
File log = new File(args[0])
that should work!

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

Take numbers from a file and sort them

I need to make my program read a file, then take the numbers in the string and sort them into an array. I can get my program to read the file and put it to a string, but that's where I'm stuck. All the numbers are on different lines in the file, but appear as one long number in the string. This is what I have so far:
public static void main(String[] args) {
String ipt1;
Scanner fileInput;
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()) {
ipt1 = fileInput.next();
System.out.print(ipt1);
}
fileInput.close();
}
catch (FileNotFoundException e) {
System.out.println(e);
}
}
I recommend reading the values in as numeric types using fileInput.nextInt() or whatever type you want them, putting them in an array and using a built in sort like Arrays.sort. Unless I'm missing a more subtle point about the question.
If your task is just to get input from some file and you're sure the file has integers, use an ArrayList.
import java.util.*;
Scanner fileInput;
ArrayList<Double>ipt1 = new ArrayList<Double>();
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()){
ipt1.add(fileInput.nextDouble()); //Adds the next Double to the ArrayList
System.out.print(ipt1.get(ipt1.size()-1)); //Prints out what you just got.
}
fileInput.close();
}
catch (FileNotFoundException e){
System.out.println(e);
}
//Sorting time
//This uses the built-in Array sorting.
Collections.sort(ipt1);
However, if you DO need to come up with a simple array in the end, but CAN use ArrayLists, you can add the following:
Double actualResult[] = new Double[ipt1.size()]; //Declare array
for(int i = 0; i < ipt1.size(); ++i){
actualResult[i] = ipt1.get(i);
}
Arrays.sort(actualResult[]);
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class SortNumberFromFile {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
System.out.println("Started at " + LocalDateTime.now());
br = new BufferedReader(new FileReader("/folder/fileName.csv"));//Read data from file named /folder/fileName.csv
List<Long> collect = br.lines().mapToLong(a -> Long.parseLong(a)).boxed().collect(Collectors.toList());//Collect all read data in list object
Collections.sort(collect);//Sort the data
writeRecordsToFile(collect, "/folder/fileName.txt");//Write sorted data to file named /folder/fileName.txt
System.out.println("Ended at " + LocalDateTime.now());
}
finally {
br.close();
}
}
public static <T> void writeRecordsToFile(Collection<? extends T> items, String filePath) {
BufferedWriter writer = null;
File file = new File(filePath);
try {
if(!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
writer = new BufferedWriter(new FileWriter(filePath, true));
if(items != null && items.size() > 0) {
for(T eachItem : items) {
if(eachItem != null) {
writer.write(eachItem.toString());
writer.newLine();
}
}
}
} catch (IOException ex) {
}finally {
try {
writer.close();
} catch (IOException e) {
}
}
}
}

Categories

Resources