How to restore a text file? - java

I want to restore the following data from the text file. The problem is only one string/line I can restore, I can't restore the rest of the data.
Here's the code :
public static String restore(String filename) throws IOException, ClassNotFoundException
{
FileInputStream fn = new FileInputStream(filename);
ObjectInputStream ob = new ObjectInputStream(fn);
String sample = (String) ob.readObject();
return sample;
}

It is hard to understand the meaning of this question, but if you just want to read lines from a .txt file and into an array, then these two methods might help.
You just need to call String[] textArray = readFromFile("yourfilename.txt");
This gives you an array with each line in the file as an element.
Scanner fScan(String filename) {
Scanner sc = null;
try {
sc = new Scanner(new File(fname));
} catch (FileNotFoundException e) {
System.out.println("File not found:" + fname + " " + e);
}
return sc;
}
String[] readFromFile (String fname) {
Scanner sc = fScan(fname);
int length = 0;
String lineCounter;
while (sc.hasNext()){
lineCounter = sc.nextLine();
length++;
}
String[] array = new String[length];
sc = fScan(fname);
for (int i = 0; i < length; i++) {
array[i] = sc.nextLine();
}
sc.close();
return array;
}

Your code does only read the first Element within your binary file.
public static void restore(String filename) throws IOException, ClassNotFoundException
{
FileInputStream fn = new FileInputStream(filename);
ObjectInputStream ob = new ObjectInputStream(fn);
String string1 = (String) ob.readObject();
String string2 = (String) ob.readObject();
}
Are you sure you did not overwrite your file while serializing it?
But as far as I understand your Question you don't want to serialize/deserialize a String-Object, rather than reading/writing a textfile.
If you just want to read/write a file, you are on the wrong way with the ObjectInputStream.
ake a look at:
http://download.oracle.com/javase/1.3/docs/api/java/io/BufferedReader.html

Related

java cannot create file by 3 methods

I have a test.txt in my active directory.I need to create three methods:
First one has to create an output file and reverse the order of the lines.
Second the order of the words
The third the order of the lines and the words.
test.txt contains the input.
I developed every method to work on its own but somehow when I call all three at the same time it doesnt seem to work.
What am i doing wrong?
This is my main:
import java.io.*;
public class DemoReverser {
public static void main (String [] args)
throws IOException, FileNotFoundException {
Reverser r = new Reverser(new File("test.txt"));
r.completeReverse(new File("out3.txt"));
r.reverseEachLine(new File("out2.txt"));
r.reverseLines(new File("out1.txt"));
} }
and this is my class.
import java.util.*;
import java.io.*;
public class Reverser {
Scanner sc = null ;
Scanner sc2 = null;
//constructor takes input file and initialize scanner sc pointing at input
public Reverser(File file)throws FileNotFoundException, IOException{
sc = new Scanner (file);
}
//this method reverses the order of the lines in the output
//prints to output file specified in argument.
public void reverseLines(File outpr)throws FileNotFoundException, IOException{
List<String> wordsarraylist = new ArrayList<String>();
while(sc.hasNextLine()){
wordsarraylist.add(sc.nextLine());
}
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str+System.lineSeparator());
}
writer.flush();
writer.close();
}
//this method reverses the order of the words in each line of the input
//and prints it to output file specified in argument.
public void reverseEachLine(File outpr)throws FileNotFoundException, IOException{
while(sc.hasNextLine()){
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
}
//this methhod reverses the order of the words in each sentence of the input
//then writes it to output file specified in argument
//then uses the output file as input and reverses the order of the sentences
//then overwrites the ouput file with the result
//the output file will contain the input sentences with their words reversed
// and the order of sentences reversed.
public void completeReverse(File outpr) throws FileNotFoundException, IOException{
while(sc.hasNextLine()){
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist2 = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist2);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist2) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
sc2 = new Scanner (outpr);
List<String> wordsarraylist = new ArrayList<String>();
while(sc2.hasNextLine()){
wordsarraylist.add(sc2.nextLine());
}
Collections.reverse(wordsarraylist);
PrintWriter erase = new PrintWriter(outpr);
erase.print("");
// erase.flush();
erase.close();
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str+System.lineSeparator());
}
writer.flush();
writer.close();
}
}
When I run the program, out1 file gests created, which is the output file for my first method but it is empty. I don't get out2 file created by second method and out3 is fine.
What am I doing wrong? What is missed
Add writer.flush(); before writer.close(); in all three methods
And other thing - Scanner is initialized with File only once in constructor. It has to be re-initialized in other methods.
sc = new Scanner (file); // the scanner should be available in all three methods
For catching exceptions, use
try{
// your code
}catch(Exception err){
err.printStackTrace();
}
After running your code, output3.txt is generated (First method call). Later Scanner is not available since end of the file has been reached.
Fix : Scanner should be re-initialized for next two methods.
EDIT: ( Updating answer with your chat feedback)
1) Create three scanners sc1,sc2 and sc3 due to your limitations. I would suggest to re-initialize the scanner in every method with the file being worked upon.
2) String reversal in easier way without using StringBuffer reverse() API ( For learning purpose)
int length = str.length();
String reverse = "";
for ( int i = length - 1 ; i >= 0 ; i-- ){
reverse = reverse + str.charAt(i);
}
It's possible if you haven't write permission where you currently trying. So you get an error when testing.
However you have made some few mistakes in code. reverseEachLine method was not worked and you should not waste code to create completeReverse method. Please note following things.
Construct the Scanner when you need it
Remember to close the Scanner
Write processed file after closing the Scanner
Remove append if not necessary in Filewriter
Remember to flush FileWriter
Identify similarities and relationships between methods (complete reverse is a combination of line reverse and word reverse)
public class MyReverser {
private File inputFile;
public MyReverser(File file) {
this.inputFile = file;
}
public void reverseLines(File outpr) throws FileNotFoundException, IOException {
Scanner sc = new java.util.Scanner(inputFile);
List<String> wordsarraylist = new ArrayList<String>();
while (sc.hasNextLine()) {
wordsarraylist.add(sc.nextLine());
}
sc.close();
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr, false);
for (String str : wordsarraylist) {
writer.write(str + System.lineSeparator());
}
writer.flush();
writer.close();
}
public void reverseEachLine(File outpr) throws FileNotFoundException, IOException {
Scanner sc = new Scanner(inputFile);
ArrayList<List<String>> wordsarraylist = new ArrayList<List<String>>();
while (sc.hasNextLine()) {
String sentence = sc.nextLine();
List words = Arrays.asList(sentence.split(" "));
Collections.reverse(words);
wordsarraylist.add(words);
}
FileWriter writer = new FileWriter(outpr, false);
for (List<String> list : wordsarraylist) {
for (String string : list) {
writer.append(string + " ");
}
writer.append(System.lineSeparator());
}
writer.flush();
writer.close();
}
public void completeReverse(File outpr) throws FileNotFoundException, IOException {
//reverse lines first
reverseLines(outpr);
//then reverse words
reverseEachLine(outpr);
}
}
The scenario here was the scanners were instance variables and once read in one of your operations method, it won't have more to read when you call the next method from Demo class. Have made the changes to read the sentences and store it in the instance, so that it can be reused in each method.
import java.util.*;
import java.io.*;
public class Reverser {
Scanner sc = null;
Scanner sc2 = null;
boolean hasReadFile;
List<String> fileLinesList;
// constructor takes input file and initialize scanner sc pointing at input
public Reverser(File file) throws FileNotFoundException, IOException {
sc = new Scanner(file);
hasReadFile = false;
fileLinesList = new ArrayList<>();
}
// this method reverses the order of the lines in the output
// prints to output file specified in argument.
public void reverseLines(File outpr) throws FileNotFoundException,
IOException {
List<String> wordsarraylist = new ArrayList<String>();
readFile();
for (String sentence : fileLinesList) {
wordsarraylist.add(sentence);
}
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist) {
writer.write(str + System.lineSeparator());
}
writer.flush();
writer.close();
}
// this method reverses the order of the words in each line of the input
// and prints it to output file specified in argument.
public void reverseEachLine(File outpr) throws FileNotFoundException,
IOException {
readFile();
for (String sentence : fileLinesList) {
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist = new ArrayList<String>(
Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
}
private void readFile() {
if (!hasReadFile) {
while (sc.hasNextLine()) {
fileLinesList.add(sc.nextLine());
}
fileLinesList = Collections.unmodifiableList(fileLinesList);
hasReadFile = true;
}
}
// this methhod reverses the order of the words in each sentence of the
// input
// then writes it to output file specified in argument
// then uses the output file as input and reverses the order of the
// sentences
// then overwrites the ouput file with the result
// the output file will contain the input sentences with their words
// reversed
// and the order of sentences reversed.
public void completeReverse(File outpr) throws FileNotFoundException,
IOException {
readFile();
for (String sentence : fileLinesList) {
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist2 = new ArrayList<String>(
Arrays.asList(words));
Collections.reverse(wordsarraylist2);
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist2) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
sc2 = new Scanner(outpr);
List<String> wordsarraylist = new ArrayList<String>();
while (sc2.hasNextLine()) {
wordsarraylist.add(sc2.nextLine());
}
Collections.reverse(wordsarraylist);
PrintWriter erase = new PrintWriter(outpr);
erase.print("");
// erase.flush();
erase.close();
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist) {
writer.write(str + System.lineSeparator());
}
writer.flush();
writer.close();
}
}

Storing input into file

I am having an issue trying to search a text file for the exact input that a user enters. I want to output the sentence not only by direct user input but i want the program to recognize some word(s) that would signal the desired text. I got searching for the keyword part down pack and working but i am only able to search the text based on the keyword. I want to search based on the keyword and the entire inputted sentence. For example if the keyword is e-mail and the user enter's what is mars e-mail? and the text file contains "mars e-mail is mars3433#aol.com, john e-mail is anonymous" i want to output mars e-mail is ... instead of both sentences. I am completely stuck trying to figure out this issue, Can anyone help me?
public static class DicEntry {
String key;
String[] syns;
Pattern pattern;
public DicEntry(String key, String... syns) {
this.key = key;
this.syns = syns;
pattern = Pattern.compile(".*(?:"
+ Stream.concat(Stream.of(key), Stream.of(syns))
.map(x -> "\\b" + Pattern.quote(x) + "\\b")
.collect(Collectors.joining("|")) + ").*");
}
}
public static void removedata(String s) throws IOException {
File f = new File("data.txt");
File f1 = new File("data2.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while ((line = br.readLine()) != null) {
if (line.contains(s)) {
System.out.println("Enter new Text :");
String newText = input.readLine();
line = newText;
System.out.println("Thank you, Have a good Day!");
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
public static void parseFile(String s) throws IOException {
File file = new File("data.txt");
Scanner forget = new Scanner(System.in);
Scanner scanner = new Scanner(file);
int flag_found = 0;
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
flag_found = 1;
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(lineFromFile);
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
}
}
if (flag_found == 0) {// input is not found in the txt file so
// flag_found remains 0
writer();
}
}
public static void writer() {
Scanner Keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
File file = new File("data.txt");
try (BufferedWriter wr = new BufferedWriter(new FileWriter(
file.getAbsoluteFile(), true))) { // Creates a writer object
// called wr
// file.getabsolutefile
// takes the filename and
// keeps on storing the old
System.out.println("I Do not know, Perhaps you want to teach me?"
+ "..."); // data
while ((Keyboard.hasNext())) {
String lines = Keyboard.nextLine();
System.out.print(" is this correct ? ");
String go = input.nextLine();
if (go.equals("no")) {
System.out.println("enter line again");
lines = Keyboard.nextLine();
System.out.print(" is this correct ? ");
go = input.nextLine();
}
else if (go.equals("yes")) {
wr.write(lines);
// wr.write("\n");
wr.newLine();
wr.close();
}
System.out.println("Thankk you");
break;
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
}
private static List<DicEntry> populateSynonymMap() {
List<DicEntry> responses = new ArrayList<>();
responses.add(new DicEntry("student", "pupil", "scholar"));
responses.add(new DicEntry("office", "post", "room"));
responses.add(new DicEntry("topics", "semester talk"));
return responses;
}
public static void getinput() throws IOException {
List<DicEntry> synonymMap = populateSynonymMap(); // populate the map
Scanner scanner = new Scanner(System.in);
String input = null;
/* End Initialization */
System.out.println("Welcome ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
String[] inputs = input.split(" ");
int flag_found = 0;
for (DicEntry entry : synonymMap) { // iterate over each word of the
// sentence.
if (entry.pattern.matcher(input).matches()) {
// System.out.println(entry.key);
parseFile(entry.key);
flag_found = 1;// Input is found
}
}
if (flag_found == 0) {// input is not found in the txt file so
// flag_found remains 0
writer();
}
}
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
getinput();
}
}
So my methods work like this, the parse file method searching the text file for the keyword in the sentence. My writer( ) writes to the file if the input is not found and my remove data ( ) erases the line and updates it with the new string upon user request. and get input is just a method to get information from the scanner.
In my opinion, additional obstacle is fact, that some word can repeat in unrelated sentences. My solution seems to be quite long for me, but it works. However when I test it, I didn't use your dicEntry. It is impossible to hard-code all synonyms, so you should reconsider this approach.
I added one class, jast as data holder for int repetition variable (see below) and particular sentence:
public class Pair {
int repetitions;
String sentence;
public Pair(int rep, String string){
repetitions = rep;
sentence = string;
}
public int getRepetitions() {
return repetitions;
}
public String getSentence() {
return sentence;
}
}
Then I wrote a method, which loop through input sentence, and file content, looking for sentence from file, in which most inputs words repeted. I pretty sure, it is not most efficient way, but I don't know another :P.
public static String getMostAppropriate(String[] input) throws IOException{
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
ArrayList<Pair> pairs = new ArrayList<>();
int repetitions = 0;
while (scanner.hasNextLine()) {
String newLine = scanner.nextLine();
String[] line = newLine.split(","); // this regex depends on your file format style,
String oneSentence = "";
for(String sentence : line){ // for sentence in file lines
for(String string : sentence.split(" ")){ // for words in these sentences
for(String word : input){ // for words from input
if(word.equals(string)){
repetitions += 1;
oneSentence = sentence;
}
}
}
pairs.add(new Pair(repetitions,oneSentence));
repetitions = 0;
}
}
return mostCommon(pairs);
}
The argument is String[] inputs form your getInput method. In return statement I called another new method, which looks for sentences with most repetitions:
public static String mostCommon(ArrayList<Pair> pairs){
Pair max = new Pair(0,"");
String result = "";
for(Pair pair : pairs){
if(pair.getRepetitions() > max.getRepetitions()){
result = pair.getSentence();
max = pair;
}else if(pair.getRepetitions()==max.getRepetitions()){
result += "; " + pair.getSentence();
}
}
return result;
}
If some sentences have same number of repetitions, it returns both(or more) connected into one sentence (sentence; sentence; etc.).
Implementation into your code I left for you, if you are interested.
As I said, I didn't use your dicEntry, still you can add it as additional loop, but chacking whole dictionary will not be too effective with my method.
Also, if I were you, I would divide some of your methods into smaller one, I mean like: read file in one, ask for additional input in another. Because it is easier to implement changes this way. You don't need to keep eye on whole method, just arguments they pass to each other.
I hope you will find something useful in my post.

PrintWriter doesn't save all characters

class Start
{
File plikIN;
Scanner in;
PrintWriter out;
Start(String input, String output)
{
plikIN = new File(input);
try{
in = new Scanner(plikIN);
out = new PrintWriter(output);
} catch (FileNotFoundException e) {System.out.println("Nie odnaleziono podanego pliku\n"+e);}
}
private void saveing() throws IOException
{
String word;
int wordLength;
String wordTable[];
char c;
while((word = in.next()) != null)
{
wordLength = word.length();
wordTable = new String[wordLength];
for(int k=0; k<wordTable.length; ++k)
{
c = word.charAt(k);
out.println(c);
}
}
out.close();
}
public static void main(String[] args) throws IOException
{
String nazwaPlikuWejsciowego = args[0];
String nazwaPlikuWyjsciowego = args[1];
Start doit = new Start(nazwaPlikuWejsciowego, nazwaPlikuWyjsciowego);
doit.saveing();
}
}
My problem is saving to file. After the saveing method above, the file does not contain any single character. When I move the out.close() to while for instance, the file contains one word. When out.close() is in for, the program saves one character only. Why?
add out.flush() before out.close().
You need to flush the bytes to disk before you close it..
This ((word = in.next()) != null) will throw an exception.
in.next() doesn't return null when there are no more elements. Take a look at the API

Read a file from a host computer [duplicate]

This question already has an answer here:
Reading a File From the Computer
(1 answer)
Closed 8 years ago.
I'm trying to read a file from the computer that is in the same folder as the source code and when I run the code is saying: File does not exist
Can you help me ?
import java.io.*;
import java.util.*;
public class Lotto1 {
static String[][] arr;
static String name, number;
public static void main(String[] args) throws IOException {
File f = new File("D:\\Filipe\\Project Final\\src\\database_lotto.txt.txt");
Scanner s;
try {
s = new Scanner(f);
BufferedReader reader = new BufferedReader(new FileReader(f));
int lines = 0;
while(reader.readLine() != null) {
lines++;
}
reader.close();
arr = new String[lines][3];
int count = 0;
//while theres still another line
while(s.hasNextLine()) {
arr[count][0] = s.next() + "" + s.next();
arr[count][1] = s.next();
arr[count][2] = s.next();
count++;
}
} catch(FileNotFoundException ex) {
System.out.println("File does not exist");
}
I've inferred what you're trying to do and recoded it, but this implementation will read the file if it is where you say it is.
public static void main(String[] args) {
final String filename = "database_lotto.txt";
final File lottoFile = new File(filename);
try (final Scanner scanner = new Scanner(lottoFile)) {
final List<String[]> storage = new ArrayList<String[]>();
while (scanner.hasNextLine()) {
storage.add(scanner.nextLine().split(" "));
}
}catch (FileNotFoundException ex) {
System.out.println("File not found :(");
}
}
Are you on Unix/Linux machine?
It is better to use File.separator instead of \, because File.separator uses the system char for a directory (\ on Win, / on Linux etc.)
Use File.exists() to check if file is there, before using it.

Find and replace a word in several text files with Java?

How can I find and replace a word in several text files, using Java?
Here's how I do it for a single String...
public class ReplaceAll {
public static void main(String[] args) {
String str = "We want replace replace word from this string";
str = str.replaceAll("replace", "Done");
System.out.println(str);
}
}
Using FileUtils from Commons IO:
String[] files = { "file1.txt", "file2.txt", "file3.txt" };
for (String file : files) {
File f = new File(file);
String content = FileUtils.readFileToString(new File("filename.txt"));
FileUtils.writeStringToFile(f, content.replaceAll("hello", "world"));
}
You can read in the file using a FileReader wrapped by a BufferedReader, pulling it in line by line, perform the same replace on the string that you show in your question, and write it back out to a new file.
This is the working code: Hope it helps!
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class TestIO {
static StringBuilder sbword = new StringBuilder();
static String dirname = null;
static File[] filenames = null;
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws FileNotFoundException, IOException{
boolean fileread = ReadFiles();
sbword = null;
System.exit(0);
}
private static boolean ReadFiles() throws FileNotFoundException, IOException{
System.out.println("Enter the location of folder:");
File file = new File(sc.nextLine());
filenames = file.listFiles();
String line = null;
for(File file1 : filenames ){
System.out.println("File name" + file1.toString());
sbword.setLength(0);
BufferedReader br = new BufferedReader(new FileReader(file1));
line = br.readLine();
while(line != null){
System.out.println(line);
sbword.append(line).append("\r\n");
line = br.readLine();
}
ReplaceLines();
WriteToFile(file1.toString());
}
return true;
}
private static void ReplaceLines(){
System.out.println("sbword contains :" + sbword.toString());
System.out.println("Enter the word to replace from each of the files:");
String from = sc.nextLine();
System.out.println("Enter the new word");
String To = sc.nextLine();
//StringBuilder sbword = new StringBuilder(stbuff);
ReplaceAll(sbword,from,To);
}
private static void ReplaceAll(StringBuilder builder, String from, String to){
int index = builder.indexOf(from);
while(index != -1){
builder.replace(index, index + from.length(), to);
index += to.length();
index = builder.indexOf(from,index);
}
}
private static void WriteToFile(String filename) throws IOException{
try{
File file1 = new File(filename);
BufferedWriter bufwriter = new BufferedWriter(new FileWriter(file1));
bufwriter.write(sbword.toString());
bufwriter.close();
}catch(Exception e){
System.out.println("Error occured while attempting to write to file: " + e.getMessage());
}
}
}

Categories