Read a file from a host computer [duplicate] - java

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.

Related

Find line number and content of a line and then find open same line number in another file JAVA

I got this code to open up a file and getting the line number, but if I want to open up another file where the content is not the same as the first file and find the same line number, how can I do that the best way? Where do I go from here?
I'm new to this site and to Java so please go easy on me...
public class c {
public static void main(String args[]) {
File file =new File("one.txt");
Scanner in = null;
try {
int counter = 0;
in = new Scanner(file);
while(in.hasNext()) {
counter++;
String line=in.nextLine();
if(line.contains("umbrella")) {
System.out.println(line + " line: " + counter);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You can just open the other file, and read the lines and increment a counter (counter2) until your counter2 reaches your counter-Variable (from above code-snippet). You also have to notice if the file hasn't ended.
The Code is has many similar Elements like the one you already used in your question.
The best way would depend on the context at which you are developing. You could just create additional instances of File and Scanner classes to operate on a different file as you already done in your code and mentioned in comment already.
Another method would be to create a class that would process this for you. In this case you could use this class for an unlimited number of files that you need to accomplish the same.
public class FileLineCounter {
public FileLineCounter( String filename)
{
try
{
f = new File(filename);
s = new Scanner(f);
}
catch(FileNotFoundException ex)
{
ex.printStackTrace();
}
}
public int getLineNumber( String item)
{
counter = 0;
while( s.hasNext())
{
counter++;
String line = s.nextLine();
if (line.contains(item))
{
break;
}
}
return counter;
}
private File f;
private Scanner s;
private int counter;
};
package FileUtil;
import FileUtil.FileLineCounter;
public class Main {
public static void main(String[] args)
{
String file1 = "one.txt";
String file2 = "two.txt";
FileLineCounter f1 = new FileLineCounter(file1);
FileLineCounter f2 = new FileLineCounter(file2);
System.out.println( file1 + " line : " + f1.getLineNumber("umbrella"));
System.out.println( file2 + " line : " + f2.getLineNumber("umbrella"));
}
}

Java filenotfoundexception asking until file is found

I have to write a program that supports extensions. I have a problem with FileNotFound Exception. Program asks about the name of the file. My task is to write an special information when there is no file like given, and ask again until user will write an existing file name. I know how to write an special information that there is no file, but I don't know how to ask again about the name of the file (I only know that it must be done using readNP method).
Here is the code:
import.java.io.*;
import java.util.* ;
class Reading{
static BufferedReader sysin =
new BufferedReader(new InputStreamReader(System.in));
String readNP() throws IOException{
// ask about file name
System.out.print("file name ");
String filename;
filename = sysin.readLine() ;
return filename.trim();
}
void read(ArrayList<Double> a) throws IOException{
// reading from file
int nr=1 ;
String name = readNP();
BufferedReader br = new BufferedReader(new FileReader(name));
String line;
while ((line = br.readLine()) != null){
a.add(new Double(line));
nr++;
}
br.close() ;
}
}
class Exceptions{
static void average(ArrayList<Double> a){
double s=0.0d;
for (int i=0; i<a.size(); i++)
s+=a.get(i).doubleValue();
System.out.println("average from numbers in table: "+s/a.size());
}
public static void main(String[] args)throws IOException{
ArrayList<Double> a = new ArrayList<Double>();
Reading r = new Reading();
try{
r.read(a);
average(a);
} catch(FileNotFoundException e){
System.out.println("File not found");
}
}
}
I would add test for existence of file name (and for that it's not the name of the directory) into your readNP() function:
String readNP() throws IOException{
// ask about file name
for (;;) {
System.out.print("file name ");
String filename;
filename = sysin.readLine();
File f = new File(filename);
if (f.exists() && !f.isDirectory()) return filename.trim();
System.out.println("file absent"); //message if the there is no file with this name
}
}

Java exception from scanning a file that was imported

I am trying to make a program that imports a text file and analyzes it to tell me if another text file has possible match up sentences. I keep running into this error when I import my file and attempt to analyze it. I am assuming that I am missing something in my code.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at PossibleSentence.main(PossibleSentence.java:30)
Heres my code too:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PossibleSentence {
public static void main(String[] args) throws FileNotFoundException{
Scanner testScan = new Scanner(System.in);
System.out.print("Please enter the log file to analyze: ");
String fileName = testScan.nextLine();
File f = new File(fileName);
Scanner scan = new Scanner(f);
String line = null;
int i = 0;
while (scan.hasNextLine()) {
String word = scan.next();
i++;
}
scan.close();
File comparative = new File("IdentifyWords.java");
Scanner compare = new Scanner(comparative);
String line2 = null;
}
}
The second scanner I havent completed yet either. Any suggestions?
We need more info to conclusively answer, but check out the documentation for next(). It throws this exception when there's no next element. My guess is it's because of this part:
String fileName = testScan.nextLine();
You're not checking if hasNextLine first.
You are passing a file argument to a Scanner object, try using an InputStream
File input = new File(/* file argument*/);
BufferedReader br = null;
FileReader fr= null;
Scanner scan = null;
try {
fr = new FileReader(input);
br = new BufferedReader(fr);
scan = new Scanner(br);
/* Do logic with scanner */
} catch (IOException e) {
/* handling for errors*/
} finally {
try {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
if (scan != null) {
scan.close();
}
} catch (IOException e) {
/* handle closing error */
}
}

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

How to restore a text file?

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

Categories