Statically Loading a .txt File - java

I understand that this question has been asked often before, and yet none of the other answers have worked for me. I am trying to statically load a .txt file in. It works wile inside the compiler (Eclipse) but after I export I get a FileNotFound exception.
I need a method that will take in a file path and load that .txt file statically, and return that file as a String. I think I have to do something with loadRecourceAsStream() but I am not sure.
Here is how I am loading it now:
public static String getFilePath(String path) {
String line = null;
String file = "";
try {
FileReader fileReader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null){
file = file + line;
}
bufferedReader.close();
} catch(FileNotFoundException e) {
System.out.println("Unable to open file " + path + "\n");
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return file;
}
Here are some other things I have tried. They all work in the compiler but not after exporting:
public static String loadFileAsString(String path){
StringBuilder builder = new StringBuilder();
try{
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while((line = br.readLine()) != null)
builder.append(line + "\n");
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path);
br.close();
}catch(IOException e){
e.printStackTrace();
}
return builder.toString();
}
And:
public static String getFile(String path) {
Scanner controlBoard = new Scanner(System.in);
controlBoard = new Scanner(Utils.class.getResourceAsStream(path));
String file = controlBoard.nextLine();
file += "\n" + controlBoard.nextLine();
file += "\n" + controlBoard.nextLine();
return file;
}
And:
public static String getFile(String path) {
System.out.println("test");
StringBuilder out = new StringBuilder();
try {
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while((line = reader.readLine()) != null) {
out.append(line + "\n");
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return out.toString();
}
Any ideas on what I should do?

I think your problem has to be related in how you are running your program when exported as I have taken your code, created a jar, run it and it worked without changing a single line. Well, I have added a main function to be able to run it. I add the code just in case but you will see that the code is the same.
package com.iseji.app.main;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main (String args[]){
System.out.println(getFilePath(args[0]));
}
public static String getFilePath(String path) {
String line = null;
String file = "";
try {
FileReader fileReader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null){
file = file + line;
}
bufferedReader.close();
} catch(FileNotFoundException e) {
System.out.println("Unable to open file " + path + "\n");
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return file;
}
}
So the question is how have you imported the file into a jar. You can really just use the "Export to" functionality of your IDE (Eclipse, IntelliJ or whatever). On the other hand I recommend you to use a life-cycle software framework like maven or gradle. Just as an example I show the gradle file that I use to create the jar (but as I say, this is not really important)
apply plugin: 'java'
sourceCompatibility = 1.5
version = '1.0'
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
}
jar {
manifest {
attributes 'Main-Class': 'com.iseji.app.main.Main'
}
}
Anyway how you export your code to a jar, the key is how the Manifest file looks like. You have to be sure that it indicates which is the main class. Verify that it is similar to:
Manifest-Version: 1.0
Main-Class: com.iseji.app.main.Main
In such a way you will be able to run it as normally passing as a parameter the file to read
java -jar ReadingFile-1.0.jar ../../src/main/resources/sample.txt
As I said at the beginning your code is fine. Just double check how you are exporting the code and running it

Related

No output from a program that compiles

I can't wrap my head around why I get zero output... The code looks correct to me, and it compiles with no problem (except for the lack of output). I have tried with absolute path. The text file is stored in the same folder as the class. Am I missing something obvious?
public class File {
public static void main(String[] args) throws FileNotFoundException {
String filename = "./inputD2.txt";
readFile(filename);
System.out.println( readFile(filename));
}
private static List<String> readFile(String filename) {
List<String> records = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
records.add(line);
}
reader.close();
return records;
}
catch (Exception e) {
System.err.format("Exception occurred trying to read '%s'.", filename);
e.printStackTrace();
return null;
}
}
}
package com.test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class FileReaderTest {
public static void main(String[] args) {
String filename = "F:\\Sixth_workspace\\Sampleproject\\src\\main\\resources\\try.txt";
System.out.println("Reading from the text file" + " " + readFile(filename));
}
private static List<String> readFile(String filename) {
List<String> records;
try {
records = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
records.add(line);
}
reader.close();
return records;
} catch (Exception e) {
System.err.println("Exception occurred trying to read '%s'." + filename);
e.printStackTrace();
return null;
}
}
}
I modified your code and got the desired output. Use the full path of the text file, here
F:\\Sixth_workspace\\Sampleproject\\src\\main\\resources\\try.txt
is my full path.
Changes:
Changed the classname
Given full path of the text file
Using java 1.8 (above 1.5 is required)

How to read a yaml file to a string with the correct indentation

I need to read a yaml file and get the content of it to a String.
As the yaml format need the right indentation, I have to get the exact content as in the file. The normal way of reading a file in java doesn't work for me.
So if anyone can tell me how to read the content of a yaml file into a String variable.
Again the question is,
How to read the content of a yaml file with the indentation and spaces and get the content of the file into a String variable in java? In other words, I need the content of the yaml file as it is to a String variable.
Anyway, you have figured it out, but here is the code for proper indentation.
package test;
import java.io.BufferedReader;
import java.io.FileReader;
public class test {
private static String FILENAME = "input.txt";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
StringBuffer stringBuffer = new StringBuffer();
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
stringBuffer.append(sCurrentLine);
stringBuffer.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(stringBuffer);
}
}

Selenium: Opening a Downloaded File in Java

I need to open and read a downloaded file using selenium and I'm not quite sure how to do it. I see answers that suggests to download the file in a selected location. Does my code really need to start from downloading the file to selected location or can it start directly after downloading?
After opening the file I must also read it. Can anyone give me an idea on how to do this? Thank you!
You can read file using following code :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample1 {
private static final String FILENAME = "E:\\test\\filename.txt";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
br = new BufferedReader(new FileReader(FILENAME));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Hope it will help you.
You can use this line of code to handel download a file from chrome and forefox browser.
public static File waitForDownloadToComplete(File downloadPath, String fileName) throws Exception {
boolean isFileFound = false;
int waitCounter = 0;
while (!isFileFound) {
logger.info("Waiting For Download To Complete....");
for (File tempFile : downloadPath.listFiles()) {
if (tempFile.getName().contains(fileName)) {
String tempEx = FilenameUtils.getExtension(tempFile.getName());
// crdownload - For Chrome, part - For Firefox
if (tempEx.equalsIgnoreCase("crdownload") || tempEx.equalsIgnoreCase("part")) {
Thread.sleep(1000);
} else {
isFileFound = true;
logger.info("Download To Completed....");
return tempFile;
}
}
}
Thread.sleep(1000);
waitCounter++;
if (waitCounter > 25) {
isFileFound = true;
}
}
throw new Exception("File Not Downloaded");
}
}

Sonar: visitFile(): How to get the source code file

I'm implementing custom script rule plugin for Sonar.
I want to make a checking rule directly for the source code
and not from checking tokens or nodes of the ASTtree.
Having the follow code:
#Override
public void visitFile() {
BufferedReader br = null;
File file = null;
String line = null;
try {
file = this.getSourceCode().getFile();
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
...
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
My problem is that the :
this.getSourceCode().getFile();
returns back null
how can I get the instance of the file for which was actually the visitFile() called?
How does 'visitFile()' works actually?

read multiple data in multiple files

I have a list of files in the directory C:\Users\Mahady\Desktop\Java 31122011\src\register\
they are like this....
100100545.txt
100545454.txt etc etc
in each file, file data are like this line by line:
Bob
1234
4834
London
9852
1
My question is, how do i read each files one by one in the directory and for each files read all lines except line 3. i would then like to merge this data in word and create letters. thanks
Detailed Answer....
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileRead {
public static void main(String[] args) {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
File folder = new File("C:/Users/Mahady/Desktop/Java 31122011/src/register/");
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line = null;
int lineCount = 0;
while (null != (line = bufferedReader.readLine())) {
lineCount++;
if (3 != lineCount) {
System.out.println(line);
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Hope this would help you.
Try this:
File dir = new File("C:\\Users\\Mahady\\Desktop\\Java 31122011\\src\\register\\");
for (string fn : dir.list()) {
FileInputStream fstream = new FileInputStream(fn);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println (strLine);
}
in.close();
}
Obviously, you will need to add exception handling code around this skeletal implementation.

Categories