I had a question regarding the File.io library. So in a class I had an assignment The Class Assignment
And I got stuck writing the part of the assignment where I need to add the ints into the output file. Here is my code right here,
import java.io.*;
import java.util.Scanner;
public class JH1_00668860 {
public static void printToScreen(String filename) {
Scanner scan = null;
try {
FileInputStream fis = new FileInputStream(filename);
scan = new Scanner(fis);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("printToScreen: can't open: " + filename);
} finally {
if (scan != null)
scan.close();
}
}// end of prin
public static void process(String inputFilename) {
String fileoutputname = null;
FileInputStream file = null;
Scanner scan = null;
FileOutputStream outputFilename = null;
OutputStream ps = null;
try {
file = new FileInputStream(inputFilename);
scan = new Scanner(file);
fileoutputname = scan.next();
System.out.println(fileoutputname + "asfasdfasdfasdf");
outputFilename = new FileOutputStream(fileoutputname);
ps = new FileOutputStream(fileoutputname);
if (scan.hasNextInt() && scan.nextInt() >= 0) {
System.out.println(scan.nextInt() + "asfs");
ps.write(scan.nextInt());
} else {
System.out.println("You have ran out of data or you have a bad value");
}
System.out.println("A file was created");
} catch (FileNotFoundException e) {
System.out.println("You ran into an exception :" + e);
} catch(IOException e) {
System.out.println("You ran into an exception :" + e);
} finally {
try {
if (file != null) {
file.close();
}
if (outputFilename != null) {
outputFilename.close();
}
if (ps != null) {
ps.close();
}
// FileInputStream st = new FileInputStream(fileoutputname);
// int contents = st.read();
// while (scan.hasNextInt()) {
// System.out.print(contents);
// }
if (scan != null) {
scan.close();
}
printToScreen(fileoutputname);
} catch (IOException e) {
System.out.println("there was an exception");
}
}
}
public static void main(String args[]) {
process("file2.txt");
}
}
When I run it the console shows This
And then I go to the file on my computer named niceJob.txt which is starting as an empty file, Eclipse then says it is going to be changed, but then when i "reload" nothing shows up.
Can anyone help me debug this bug(or if it is some other thing that is happening?) Any help would be appreciated. Thanks
After your code ps.write(scan.nextInt()); try to put ps.write.flush(); or ps.flush();
EDIT:
If it still doesn't work add imports:
import java.io.BufferedWriter;
import java.io.FileWriter;
and change ps.write(scan.nextInt()); to
BufferedWriter writer = new BufferedWriter(new FileWriter(inputFilename));
writer.write(Integer.toString(scan.nextInt));
writer.newLine();
writer.flush();
Related
Suppose that file.txt only contains "Hello". When I compile the Java code, it shows
Error: This method must return a result of type java.lang.String in line5.
When I print in readTxt function, that works, it can show "Hello".
I already check the result is correctly String type, but it also shows compiler error. How can I make the return value to the main function?
import java.io.*;
import java.lang.String;
public class ReadTxtFile {
public static String readTxt(String filePath) {
try {
File file = new File(filePath);
if(file.isFile() && file.exists()) {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(isr);
String lineTxt = null;
lineTxt = br.readLine();
//System.out.println(lineTxt);
br.close();
return lineTxt;
} else {
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
String filePath = "C:/file.txt";
String fileword = readTxt(filePath);
System.out.println(fileword);
}
}
You promised to return a String from your method, so you now have to do that. The only way around that promise is to throw an exception.
public static String readTxt(String filePath) { // Here you promise to return a String
try {
...
if(file.isFile() && file.exists()) {
...
return lineTxt; // Here you return a String as promised
} else {
// Here you're missing either return or throw
}
} catch (Exception e) {
// Here you're missing either return or throw
}
}
This is fundamentally a design problem - what should your method do if it fails to read the file for some reason? Return a special string like "Error"? Return null? Fail and throw and exception? Something else?
Answer that to yourself and it will be clear to you how to fix the code.
There are several best practices you should follow that will prevent future error. I have tried to cover them. Not saying mine is the perfect one, but you will get the idea.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class StackOverFlow {
public static void main(String[] args) {
try {
String sText = getFileText("C:/file.txt");
System.out.println("Text is: " + sText);
} catch (FileNotFoundException e) {
System.out.println("File not Found");
} catch (IOException e) {
System.out.println("#Error while reading text: " + e.getMessage());
}
}
private static String getFileText(String filePath) throws FileNotFoundException, IOException {
File file = new File(filePath);
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
}finally {
reader.close();
}
return new String(stringBuilder);
}
}
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();
}
}
}
I have a text file with serialized objects written it. The file contains data like this -
line[com.high.3449%]
line[com.high.58850?]
line[com.high.47646%]
I want to read this and store 1 by 1 in an arraylist. But when I read it I am just able to read the first line which is line[com.high.3449%] but not everything. I am using below logic to read -
List<MyData> myobjects1 = new ArrayList<MyData>();
List<MyData> myobjects2 = new ArrayList<MyData>();
FileInputStream fin = new FileInputStream("/storage/200B-431F/Documents/MyData.txt");
ois = new ObjectInputStream(fin);
try {
myobjects1 = (List<MyData>) ois.readObject();
while (myobjects1 != null) {
myobjects2.addAll(myobjects1);
Log.d("hi", "second arraylist " + myobjects2);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois.close();
server.sendData(myobjects2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e) {}
Can someone help me how to read all the data and store in the arraylist myobjects2?
The issue seems to be related to your loop when you read back the data. There is no need to loop (it will loop forever)
Instead of
myobjects1 = (List<MyData>) ois.readObject();
while (myobjects1 != null) {
myobjects2.addAll(myobjects1);
...
You should use
myobjects1 = (List<MyData>) ois.readObject();
if (myobjects1 != null) {
myobjects2.addAll(myobjects1);
}
If you want to loop through the myobjects you need to use something like
for (MyData myData : myobjects1) {
myobjects2.add(myData);
}
Am adding the code I used to test the answer.
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class LoadFileObject {
public static class MyData implements Serializable {
private String line, content;
public MyData(String line, String content) {
setLine(line);
setContent(content);
}
public String getLine() {
return line;
}
public void setLine(String line) {
this.line = line;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content= content;
}
public String toString() {
return (line+content);
}
}
#Test
public void doWork() throws Exception {
List<MyData> myobjects1 = new ArrayList<MyData>();
myobjects1.add(new MyData("l1", "content1"));
myobjects1.add(new MyData("l2", "content2"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("mydata.txt"));
oos.writeObject(myobjects1);
oos.close();
List<MyData> myobjects2 = new ArrayList<MyData>();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("mydata.txt"));
myobjects2 = (List<MyData>) ois.readObject();
System.out.println("read:" + myobjects2.size());
for (MyData myData : myobjects2) {
System.out.println("myData line:" + myData.getLine() + " content:" + myData.getContent());
}
}
}
try this :
FileInputStream fis = null;
BufferedReader reader = null;
try {
fis = new FileInputStream("/storage/200B-431F/Documents/MyData.txt/CPU.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
System.out.println(line);
line = reader.readLine();
// here line variable will hold the data for each line of your text file
// i.e you can add the string to the arrayList here
myObjects2.add(line);
}
} catch (FileNotFoundException ex) {
}
catch (IOException ex) {
}
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
I'm trying to make a class that takes info from the GUI this saves it to a text file which I use as my "Database" but for some reason the PrintWriter object doesn't write the new data in the file. here's my code
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class IO {
File f = new File("DB.txt");
PrintWriter write;
Scanner input;
String[][] data;
String nameToSearch;
// search constructor
public IO(String name) {
super();
nameToSearch = name;
try {
input = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File not found please restart the program");
}
data = new String[linesCounter()][2];
for (int i = 0; i < linesCounter(); i++) {
data[i][0] = input.nextLine();
data[i][1] = input.nextLine();
}
}
public IO(String name, String number) {
try {
write = new PrintWriter(new FileWriter(f, true));
} catch (IOException e) {
System.out.println("Error");
}
write.println(name);
write.println(number);
}
int linesCounter() {
try {
input = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File not found please restart the program");
}
int counter = 0;
while (input.hasNext()) {
input.nextLine();
counter++;
}
return counter / 2;
}
int contactFinder() {
for (int i = 0; i < linesCounter(); i++)
if (data[i][0].equalsIgnoreCase(nameToSearch))
return i;
return -1;
}
String nameGetter() {
return data[contactFinder()][0];
}
String numGetter() {
return data[contactFinder()][1];
}
}
you need to close the printwriter after you have finished writing into the file using printwriter.close()
try {
write = new PrintWriter(new FileWriter(f, true));
write.println(name);
write.println(number);
write.close();
} catch (IOException e) {
System.out.println("Error");
}
}
EDIT:
For your NoSuchElement Excepion, you should check if there is a nextline in the file before invoking Scanner.nextline() using Scanner.hasNextLine().
for (int i = 0; i < linesCounter(); i++) {
if(input.hasNextLine()){
data[i][0] = input.nextLine();
data[i][3] = input.nextLine();
}
}
It's possible the PrintWriter never got flushed. You can do this manually with
write.flush();
That will ensure the buffer gets written to the file.