Cannot find file on netbeans - java

I'm trying to access a data file to get questions and answers for my "Quiz" application.
If I access the file from the one on my desktop, it works fine. If I drag and drop the file into my netbeans, I cannot seem to access it.
The file is in the package "quiz" along with my other classes.
Here's the code that works but I want to use the netbeans file.
String fileName = "C:/Users/Michael/Desktop/QUIZ.DAT";
try {
//Make fileReader object to read the file
FileReader file = new FileReader(new File(fileName));
BufferedReader fileStream = new BufferedReader(file);
} catch (Exception e) {
System.out.println("File not found");
}
To try and access the file on netbeans I use this but it cannot find it.
String fileName = "quiz/Quiz.DAT";

Try this, where MyClass is the class name. I have assumed the quiz.dat file is in the same package of the class.
InputStream f = MyClass.class.getResourceAsStream("QUIZ.DAT");
BufferedReader bReader = new BufferedReader(new InputStreamReader(f));
StringBuffer sbfFileContents = new StringBuffer();
String line = null;
while ((line = bReader.readLine()) != null) {
sbfFileContents.append(line);
}
System.out.println(sbfFileContents.toString());

JJPA provided proper code. But let me enhance it better.
Project
com.io
test.txt
com.root
AccessFile.java
This is my program structure. I want to access file from package io So here is the code.
package com.root;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class AccessFile {
public static void main(String args[]){
try{
InputStream f = AccessFile.class.getResourceAsStream("../io/test.txt");
BufferedReader bReader = new BufferedReader(new InputStreamReader(f));
StringBuffer sbfFileContents = new StringBuffer();
String line = null;
while ((line = bReader.readLine()) != null) {
sbfFileContents.append(line);
}
bReader.close();
f.close();
System.out.println(sbfFileContents.toString());
}catch(Exception e){
e.printStackTrace();
}
}
}

If you are trying to read a file in your JAVA project and netbeans is not able to find it, put the file in the root directory of your project and it should be able to find it.

Related

Java: reading file and then writting data on a text file

How to read a file and then write the data into a .txt file in java? Below is my code. I am reading a file with extension .ivt. There are some tables in .ivt and reset is a text that describes what data is all about. I have to read the text stored in the file and then write it on a text file. I was able to get the data and write it on text file as well. But, when I open the text file and look at what is written, I see many lines of random symbols and spaces. Then, few lines are converted from English to French. I am struggling to find why this is happening. Does this problem occurs while reading data? or is there something wrong with the code?
package description;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
public class FileDescription
{
public static void main(String[] args)
{
// create variables
ArrayList<String> fileLines = new ArrayList<>();
String currLine;
// create file
File file = new File("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\Products.ivt");
FileInputStream fis = null;
BufferedReader br = null;
try
{
fis = new FileInputStream(file);
// construct buffered reader
br = new BufferedReader(new InputStreamReader(fis));
}
catch (FileNotFoundException e)
{
}
try
{
while((currLine = br.readLine()) != null)
{
// add line to the arrayList
fileLines.add(currLine);
}
}
catch (IOException e)
{
}
finally
{
// close buffered reader
try
{
br.close();
}
catch (IOException e)
{
}
}
// write ArrayList on file
PrintWriter pw = null;
try
{
pw = new PrintWriter("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\ProductsO.txt");
}
catch (IOException e)
{
}
for (int i = 0; i < fileLines.size(); i++)
{
pw.println(fileLines.get(i));
}
}
}
The code seems correct. Just remember to close output writer too. Without specify anything else, you are using plaftorm encoding. I think it's an encoding problem. You can try to read and write in UTF-8 encoding.
For the buffered reader
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("filename.txt"), StandardCharsets.UTF_8));
And for the writer
pstream = new PrintWriter(new OutputStreamWriter(
new FileOutputStream("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\ProductsO.txt"), StandardCharsets.UTF_8), true);
To edit result, use an editor with UTF-8.
Reference 1
Reference 2

File Reader Method

So I wrote this file reader method that should return a string of everything that is in the file, but it isn't working properly. Writing into the file works perfectly, but this reading method doesn't. What the method does currently is it reads the last string/text added, but it does not read the file from start to finish. 'br' is my bufferedReader, which is declared somewhere else in the same class.
Here's how br is defined:
private static FileInputStream fis;
private static BufferedReader br;
and then in the constructor:
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
Here's the method:
public String readStuff(){
String line = "";
String r = "";
try{
while((line = br.readLine()) != null){
System.out.println(line + " read ");
r+= line;
}
//br.close(); JDK 7 does this automatically apparently
}catch(IOException e){
e.printStackTrace();
System.out.println("Error at readStuff!");
}
return r;
I know I'm making either a logic mistake or some obvious error, I just don't know where.
If you want to read the entire file twice, you will have to close it and open new streams/readers next time.
Those streams/readers should be local to the method, not members, and certainly not static.
Using File and FileReader You can Read / Write File From Dir.
you can get File using File class object
File file = new File("file.txt");
and After Process to read that file
FileReader fr = new FileReader(file);
There are Whole Code to read File...
File file = new File("G:\\Neon\\data.txt");
FileReader fr = new FileReader(file);
String data = "";
while((i = fr.read()) != -1)
{
data = data + (char)i;
}
System.out.println(data);

Cannot find file in netbeans + glassfish project

Here it is my folder project
I would like to read the file book-form.html which is in the directory web of my project and put it in a String.
This is how I call my function 'getFileContent':
String content = getFileContent("web/book-form.html");
And this is the function:
public String getFileContent(String filePath){
String line, content = new String();
try {
File file = new File(filePath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null){
content += line;
}
br.close();
fr.close();
} catch(IOException e){
System.out.println(e.getMessage());
}
return content;
}
My problem is that netbeans tell me that it cannot find my file book-form.html
Any ideas ?
File path to resource in our war/WEB-INF folder?
Also you should close stream in a final block or use try-with-resource if you use jdk 7+
I find the way to do it:
Basically the program is in the main folder of Glassfish, so it's needed to put the entire path of your file from the root of your system to allow the program to find your file.

Java fileinput (read and write) to a file looping thru each line

I have this method that access a exisitng file, loop thru each line and replace (string to string) a certain line if the condition is met:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
private void UpdateConfig() {
try {
FileInputStream fstream = new FileInputStream("c:\\user\\config.properties");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.contains("FTPDate=2014/07/01 00:59:00")) {
System.out.println("FILE " + strLine);
strLine.replace("FTPDate=2014/07/01 00:59:00", "FTPDate=2014/09/10 00:00:00");
//strLine.replace("((19|20)\\d\\d/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])) ([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])", "2014/09/10 00:00:00");
System.out.println("FILE " + strLine);
}
}
in.close();
} catch (Exception e) {
}
}
In the sysout it seems its being replaced:
FILE FTPDateTejas=2014/07/01 00:59:00
FILE FTPDateTejas=2014/09/10 00:00:00
But when I check the file, the date still stays the same. Am I missing something? anyone knows what I missed out? thank you
When you are doing:
strLine = br.readLine() it loads the next line from the BufferedReader into memory. This means that you have your data on disk and in memory and that those two are not linked to each other in any way. When doing modifications on strLine I believe you have in your code:
strLine = strLine.replace("FTPDate=2014/07/01 00:59:00", "FTPDate=2014/09/10 00:00:00");
As replace doesn't modify the contents of the objects on which it is being called but returns a new String objects (Strings are immutable). So what that does it creates a new object but does not modify your on disk data (as I said, it's not linked to it any more!).
You could think "ok then how do I link those two and override the file in place?". Well Java does provide random file access as described in the doc but the only thing you can do with it is modify characters at a certain position, you cannot insert things in the middle. So what you would have to do is read the rest of your file, make your modification and then append that rest of the file, yes you need to shift things in case your new string with which you are substituting would be shorter/longer than what you are replacing.
That's why an easier solution would be to:
open a new file to write to
write line by line to it (the strings after the replace)
delete the old file and rename the new file
Without copying the file the code would look something like this:
private void UpdateConfig() {
File fstream = new File("c:\\user\\config.properties");
File file = new File("c:\\user\\config.properties-new");
try {
file.createNewFile();
} catch (IOException e) {
// handle
}
try (FileReader in = new FileReader(fstream);
FileWriter fw = new FileWriter(file.getAbsoluteFile())) {
try (BufferedReader br = new BufferedReader(in);
BufferedWriter bw = new BufferedWriter(fw)) {
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.contains("FTPDate=2014/07/01 00:59:00")) {
System.out.println("FILE " + strLine);
strLine = strLine.replace("FTPDate=2014/07/01 00:59:00",
"FTPDate=2014/09/10 00:00:00");
//strLine.replace("((19|20)\\d\\d/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])) ([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])", "2014/09/10 00:00:00");
bw.write(strLine);
System.out.println("FILE " + strLine);
}
}
}
// copy files here
} catch (IOException e) {
// handle
}
}
There might be some logical/syntactic problems as I was writing in in a plain text editor. I modified the code a bit to use Java 7's try-with-resources, which is a cleaner way of closing resources than what you were doing - in your code when an exception would be thrown the stream might not had been closed.

How to read a text file directly from Internet using Java?

I am trying to read some words from an online text file.
I tried doing something like this
File file = new File("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner scan = new Scanner(file);
but it didn't work, I am getting
http://www.puzzlers.org/pub/wordlists/pocket.txt
as the output and I just want to get all the words.
I know they taught me this back in the day but I don't remember exactly how to do it now, any help is greatly appreciated.
Use an URL instead of File for any access that is not on your local computer.
URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner s = new Scanner(url.openStream());
Actually, URL is even more generally useful, also for local access (use a file: URL), jar files, and about everything that one can retrieve somehow.
The way above interprets the file in your platforms default encoding. If you want to use the encoding indicated by the server instead, you have to use a URLConnection and parse it's content type, like indicated in the answers to this question.
About your Error, make sure your file compiles without any errors - you need to handle the exceptions. Click the red messages given by your IDE, it should show you a recommendation how to fix it. Do not start a program which does not compile (even if the IDE allows this).
Here with some sample exception-handling:
try {
URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner s = new Scanner(url.openStream());
// read from your scanner
}
catch(IOException ex) {
// there was some connection problem, or the file did not exist on the server,
// or your URL was not in the right format.
// think about what to do now, and put it here.
ex.printStackTrace(); // for now, simply output it.
}
try something like this
URL u = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
InputStream in = u.openStream();
Then use it as any plain old input stream
What really worked to me: (source: oracle documentation "reading url")
import java.net.*;
import java.io.*;
public class UrlTextfile {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://yoursite.com/yourfile.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Using Apache Commons IO:
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public static String readURLToString(String url) throws IOException
{
try (InputStream inputStream = new URL(url).openStream())
{
return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
}
}
Use this code to read an Internet resource into a String:
public static String readToString(String targetURL) throws IOException
{
URL url = new URL(targetURL);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(url.openStream()));
StringBuilder stringBuilder = new StringBuilder();
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null)
{
stringBuilder.append(inputLine);
stringBuilder.append(System.lineSeparator());
}
bufferedReader.close();
return stringBuilder.toString().trim();
}
This is based on here.
For an old school input stream, use this code:
InputStream in = new URL("http://google.com/").openConnection().getInputStream();
I did that in the following way for an image, you should be able to do it for text using similar steps.
// folder & name of image on PC
File fileObj = new File("C:\\Displayable\\imgcopy.jpg");
Boolean testB = fileObj.createNewFile();
System.out.println("Test this file eeeeeeeeeeeeeeeeeeee "+testB);
// image on server
URL url = new URL("http://localhost:8181/POPTEST2/imgone.jpg");
InputStream webIS = url.openStream();
FileOutputStream fo = new FileOutputStream(fileObj);
int c = 0;
do {
c = webIS.read();
System.out.println("==============> " + c);
if (c !=-1) {
fo.write((byte) c);
}
} while(c != -1);
webIS.close();
fo.close();
Alternatively, you can use Guava's Resources object:
URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
List<String> lines = Resources.readLines(url, Charsets.UTF_8);
lines.forEach(System.out::println);
corrected method is deprecated now. It is giving the option
private WeakReference<MyActivity> activityReference;
here solution will useful.

Categories

Resources