writeToFile is writing to file twice - java

I have tried out.append(s); However my problems grow out of control. Anyone else see anything my eyes are missing?
public void writeToFile()
{
PrintWriter out = null;
try
{
out = new PrintWriter(new BufferedWriter(new FileWriter("course.txt", true)));
for (String courseName:courseData.keySet())
{
Course course = courseData.get(courseName);
if (!course.isEmpty())
{
ArrayList<String> students = course.getStudentList();
for (String s : students)
{
out.println(courseName + "<<<<" + s);
}
}
else
{
out.println(courseName + "<<<<");
}
}
} catch (IOException ex)
{
Logger.getLogger(CourseApp.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
out.close();
}
}
My text file should look like this after I make an entry.
However this is the result I actually get.

//use pw.flush() at the end to avoid multiple copies
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.FileHandler;
public class MergeFiles {
public static void main(String[] arg) throws IOException
{
File dir=new File("E:\\videos\\assignments\\fileWork");
File file = new File("E:\\videos\\assignments\\fileWork\\MergeAllAssignments.txt");
file.getParentFile().mkdirs();
PrintWriter pw=new PrintWriter(file);
String[] fileNames=dir.list();
for(String files:fileNames)
{
System.out.println("Reading file "+files);
File f=new File(dir,files);//instance of file to read
BufferedReader br=new BufferedReader(new FileReader(f));//f>>filereader>>bufferedReader
String line=br.readLine();//reading line by line
while(line!=null)
{
System.out.println(line);
pw.println(line);
line=br.readLine();
}
pw.println("\r\n\n\r\n next days assignment>>>>>>>>>>>>>>>>>>>\r\n\r\n\r\n\r\n\r\n");
//to write everything in pw object to destinatio
}
pw.flush();
pw.close();
System.out.println("Copying completed");
}
}

Related

Encoding with UTF-16 in Java

I'm trying to read/write a .txt file in UTF-16 so that I can input/output Japanese characters into/from my program. I have read many similar questions, articles and the Java Docs, virtually copied their code and still can't figure out where I am going wrong. If I output it to the console, or whenever I check the contents of the file (using the correct encoding) all I see is a '?' in place of 'あ'.
Application class:
public class App {
public static void main(String[] args) {
String[] s = {"あ"}; //A test String array
FileReader.write("unicode.txt", "UTF-16", s, false);
System.out.println("File: " + FileReader.read("unicode.txt", "UTF-16") + " Hard-coded example: あ");
}
}
FileReader class:
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.nio.charset.Charset;
public class FileReader {
public static String[] read(String fileName, String encoding) {
ArrayList<String> content = new ArrayList<String>();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), Charset.forName(encoding).newDecoder()))) {
for(String s = reader.readLine(); s != null; s = reader.readLine()) {
content.add(s);
}
reader.close();
} catch(IOException e) {
System.out.println("An IOException(Input) has been thrown.");
e.printStackTrace();
}
return convertToStringArray(content);
}
public static void write(String fileName, String encoding, String[] content, boolean append) {
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, append), Charset.forName(encoding).newEncoder()))) {
for(String s : content) {
writer.write(s);
writer.newLine();
}
writer.close();
} catch (IOException e) {
System.out.println("An IOException(appending=" + append + ") has been thrown.");
e.printStackTrace();
}
}
private static String[] convertToStringArray(ArrayList<String> list) {
String[] array = new String[list.size()];
list.toArray(array);
return array;
}
}

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

cannot create a txt file

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")

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