How to given a fixed path to eclipse - java

Code:
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
How could I modify this code to take a file from a fixed location?
Equivalent scanner example:
Scanner in = new Scanner(new InputStreamReader(System.in));
Scanner in = new Scanner(new FileReader("C:\\Users\\Max\\Desktop\\yes.txt"));

if you only want the whole text in one string than you can use the FileInputStream
FileInputStream inputStream = new FileInputStream("foo.txt");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
if you want to read the file line bye line use the BufferdReader in Connection with StringBuilder
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
}finally {
br.close();
}
Note:
The examples are taken from #Knubo and the whole answer and further Information can be found here

To read file using Scanner class.
Try this.
Scanner input=null;
try{
input=new Scanner(new File("your_file_path\yes.txt"));
} catch(Exception ex){
System.out.println(ex.getMessage());
}
while(input.hasNext()){
System.out.println(input.next());
}
input.close();

Related

How to delete and override a file in java?

I want to rename and delete "products2.txt" to "products.txt".
if I test with another files "test1" and "test2", in the same directory, will work fine, but with my filles "products" and "products2", doesn't work, not even to delete the file with file.delete();
try{
File file = new File("C:\\Users\\J3TyX\\Desktop\\proiect JAVA PENTA\\products.txt");
Scanner sc = new Scanner(file);
File tempFile = new File("C:\\Users\\J3TyX\\Desktop\\proiect JAVA PENTA\\products2.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
System.out.println("ID number:");
int delete = in.nextInt();
String lineToRemove = Objects.toString(delete,null);
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
String trimmLine[] = trimmedLine.split(" ");
String part1 = trimmLine[0];
if(!part1.equals(lineToRemove)) {
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.flush();
writer.close();
reader.close();
sc.close();
file.delete();
tempFile.renameTo(file);
}catch (IOException e){
e.printStackTrace();
}

How to display all lines of text from a file instead of stopping at the end of a line?

The code below only brings up the first line of code and stops. I would like to return each line of code until there are no more.
private String GetPhoneAddress() {
File directory = Environment.getExternalStorageDirectory();
File myFile = new File(directory, "mythoughtlog.txt");
//File file = new File(Environment.getExternalStorageDirectory() + "mythoughtlog.txt");
if (!myFile.exists()){
String line = "Need to add smth";
return line;
}
String line = null;
//Read text from file
//StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(myFile));
line = br.readLine();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
return line;
}
You could loop over the results of readLine() and accumulate them until you get a null, indicating the end of the file (BTW, note that your snippet neglected to close the reader. A try-with-resource structure could handle that):
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
String line = br.readLine();
if (line == null) {
return null;
}
StringBuilder retVal = new StringBuilder(line);
line = br.readLine();
while (line != null) {
retVal.append(System.lineSeparator()).append(line);
line = br.readLine();
}
return retVal.toString();
}
if you're using Java 8, you can save a lot of this boiler-plated code with the newly introduced lines() method:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
A considerably less verbose solution:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
StringBuilder retVal = new StringBuilder();
while ((line = br.readLine()) != null) {
retVal.append(line).append(System.lineSeparator());
}
return retVal.toString();
}

How to read a file?

private void getInput() throws IOException {
InputStream resourceAsStream = this.getClass().getResourceAsStream(
"aaa.txt");
BufferedReader br = new BufferedReader(new FileReader(
resourceAsStream.toString()));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
System.out.println(everything);
} finally {
br.close();
}
}
The file aaa.txt is in the same project and it cannot be read, I have java.lang.NullPointerException when I execute that.
Only do this
BufferedReader br = new BufferedReader(new FileReader("aaa.txt"));
But put the file in the filereader instead.
Hope it helpt.

Java File I/O: If a 'hard-coded' file is not found, how do I prompt the user for the file?

So my question is just how the title goes. Below is a snippet of my code. I understand that I'm supposed to use try/catch but in my catch, I'm not sure what to do in it. I'm getting an error /HERE/ saying that a BufferedReader cannot take in an InputStream. I want to continue using a BufferedReader, so is there any other class that I could instantiate w/in my new BufferedReader so that my compiler will be happy? Any help will be much appreciated, thank you!
//reads in 'dictionary' file
BufferedReader bReader;
try
{
bReader = new BufferedReader
(new FileReader("unsortedWords.txt"));
}
catch (FileNotFoundException e)
{
System.out.print("Enter name of dictionary file: ");
bReader = new BufferedReader
(new FileReader(System.in)); /*HERE*/
}
Maybe this:
File file = new File("unsortedWords.txt");
if(file.exists())
{
// do something
}
else
{
// prompt for file
// if command line you can use Scanner or an InputStreamReader
// if GUI you can use a File Chooser.
}
If you are unsure how to do the command line or GUI thing then just ask me and I will post the rest of the code.
[EDIT]:
I see you are doing the command line, so you can try this:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
[EDIT]: Sample Class (yes it has bad design, but I wrote it quickly):
import java.io.*;
public class Temp
{
public static void main(String[] args) throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Hello World!");
String temp = br.readLine();
System.out.println("Your line : \"" + temp + "\"");
}
}
[EDIT]:
Here is a class that I made which should work for you.
import java.io.*;
public class Temp
{
public static void main(String[] args) throws IOException
{
String fileName = "RandomFileThatDoesntExist";
File file = new File(fileName);
if(file.exists())
{
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null)
{
System.out.println(line);
}
}
else
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter file Name:");
String line;
while(true)
{
line = br.readLine();
File myFile = new File(line);
if(myFile.exists())
break;
else
System.out.println("Error, file doesn't exist!");
}
FileReader fr = new FileReader(line);
BufferedReader br2 = new BufferedReader(fr);
System.out.println("File contents:");
while((line = br2.readLine()) != null)
{
System.out.println(line);
}
}
}
}
Screenshot:
I don't think you have posted the in-use code, your error should be related to creating a FileReader from an ImputStream.
Use InputStreamReader:
BufferedReader in
= new BufferedReader(new InputStreamReader(System.in));
exactly as given in the docs :)

Read data from a text file using Java

I need to read a text file line by line using Java. I use available() method of FileInputStream to check and loop over the file. But while reading, the loop terminates after the line before the last one. i.e., if the file has 10 lines, the loop reads only the first 9 lines.
Snippet used :
while(fis.available() > 0)
{
char c = (char)fis.read();
.....
.....
}
You should not use available(). It gives no guarantees what so ever. From the API docs of available():
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
You would probably want to use something like
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null)
process(str);
in.close();
} catch (IOException e) {
}
(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)
How about using Scanner? I think using Scanner is easier
private static void readFile(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Read more about Java IO here
If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
// Do something with line
}
(Note that this code doesn't handle exceptions or close the stream, etc)
String file = "/path/to/your/file.txt";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
// Uncomment the line below if you want to skip the fist line (e.g if headers)
// line = br.readLine();
while ((line = br.readLine()) != null) {
// do something with line
}
br.close();
} catch (IOException e) {
System.out.println("ERROR: unable to read file " + file);
e.printStackTrace();
}
You can try FileUtils from org.apache.commons.io.FileUtils, try downloading jar from here
and you can use the following method:
FileUtils.readFileToString("yourFileName");
Hope it helps you..
The reason your code skipped the last line was because you put fis.available() > 0 instead of fis.available() >= 0
In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:
private List<String> loadFile() {
URI uri = null;
try {
uri = ClassLoader.getSystemResource("example.txt").toURI();
} catch (URISyntaxException e) {
LOGGER.error("Failed to load file.", e);
}
List<String> list = null;
try (Stream<String> lines = Files.lines(Paths.get(uri))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
return list;
}
//The way that I read integer numbers from a file is...
import java.util.*;
import java.io.*;
public class Practice
{
public static void main(String [] args) throws IOException
{
Scanner input = new Scanner(new File("cards.txt"));
int times = input.nextInt();
for(int i = 0; i < times; i++)
{
int numbersFromFile = input.nextInt();
System.out.println(numbersFromFile);
}
}
}
Try this just a little search in Google
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Try using java.io.BufferedReader like this.
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileName)));
String line = null;
while ((line = br.readLine()) != null){
//Process the line
}
br.close();
Yes, buffering should be used for better performance.
Use BufferedReader OR byte[] to store your temp data.
thanks.
user scanner it should work
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
public class ReadFileUsingFileInputStream {
/**
* #param args
*/
static int ch;
public static void main(String[] args) {
File file = new File("C://text.txt");
StringBuffer stringBuffer = new StringBuffer("");
try {
FileInputStream fileInputStream = new FileInputStream(file);
try {
while((ch = fileInputStream.read())!= -1){
stringBuffer.append((char)ch);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File contents :");
System.out.println(stringBuffer);
}
}
public class FilesStrings {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("input.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
while ((data = br.readLine()) != null) {
result = result.concat(data + " ");
}
System.out.println(result);
File file = new File("Path");
FileReader reader = new FileReader(file);
while((ch=reader.read())!=-1)
{
System.out.print((char)ch);
}
This worked for me
Simple code for reading file in JAVA:
import java.io.*;
class ReadData
{
public static void main(String args[])
{
FileReader fr = new FileReader(new File("<put your file path here>"));
while(true)
{
int n=fr.read();
if(n>-1)
{
char ch=(char)fr.read();
System.out.print(ch);
}
}
}
}

Categories