I'm doing example from the book
"Java The Complete Reference Ninth Edition"
that demonstrates FileInputStream using try-with resources.
In the output I've got "I/O Error: java.io.FileNotFoundException: C:\Users\user\Documents\NetBeansProjects\JavaExam\FileInputStreamDemo.java (Can't find file)".
The code:
package javaexam;
import java.io.*;
class FileInputStreamDemo {
public static void main(String args[]) {
int size;
// Use try-with-resources to close the stream.
try ( FileInputStream f =
new FileInputStream("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaExam\\FileInputStreamDemo.java"))
{
System.out.println("Total Available Bytes: " + (size = f.available()));
int n = size/40;
System.out.println("First " + n + " bytes of the file one read() at a time");
for (int i = 0; i < n; i++) {
System.out.print((char) f.read());
}
System.out.println("\nStill Available: " + f.available());
System.out.println("Reading the next " + n + " with one read(b[])");
byte b[] = new byte[n];
if (f.read(b) != n) {
System.err.println("couldn't read " + n + " bytes.");
}
System.out.println(new String(b, 0, n));
System.out.println("\nStill Available: " + (size = f.available()));
System.out.println("Skipping half of remaining bytes with skip()");
f.skip(size/2);
System.out.println("Reading " + n/2 + " into the end of array");
if (f.read(b, n/2, n/2) != n/2) {
System.err.println("couldn't read " + n/2 + " bytes.");
}
System.out.println(new String(b, 0, b.length));
System.out.println("\nStill Available: " + f.available());
} catch (IOException e) {
System.out.println("I/O Error: " + e);
}
}
}
I think your issue might be that you're using backslashes. I'm not certain, though. Try using a BufferedReader instead.
File file = new File("C:/Users/user/Documents/NetBeansProjects/JavaExam/FileInputStreamDemo.java");
BufferedReader bufferedreader = new BufferedReader(new FileReader(file));
Using this you should be able to read it a lot more easily, and line by line instead of byte by byte.
The file you are looking should be in the src folder under package javaexam. Otherwise it won't be compiled. By the Java conventions each public class should have the name of the file and reside in the folder with the name of the package.
new FileInputStream("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaExam\\src\\javaexam\\FileInputStreamDemo.java"))
Related
I wrote a program to read from a specific file and was wondering how would I display a custom message if that file were to not be found. What I have currently does not work, could someone explain why?
try {
//create the file writer
Fwrite = new FileWriter(file);
Fwrite.write("Student Name \t\t\t Test Score \t Grade\n");
for (int i = 0; i < size; i++) {
Fwrite.write(students[i].getStudentLName() + ", " + students[i].getStudentFName() +
" \t\t\t "+ students[i].getTestScore() + " \t\t " + students[i].getGrade() + "\n");
}
Fwrite.write("\n\nHighest Test Score: " + highestScore + "\n");
Fwrite.write("Students having the highest test score\n");
//writes the test scores in descending order
for (int i = 0; i < size; i++) {
if (students[i].getTestScore() == highestScore) {
Fwrite.write(students[i].getStudentLName() + ", ");
Fwrite.write(students[i].getStudentFName() + "\n");
}
}
//catches any errors
} catch (IOException e) {
System.err.println("File mot Found!");
e.printStackTrace();
}
//try catch method to catch any errors
System.out.println("File Complete!");
//close file
Fwrite.close();
To show file not found exception change catch block to this
catch(FileNotFoundException e){
e.printStackTrace();
}
This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.
CHECK THIS Link https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html
What I am doing is creating two nodes that will talk to each other through text files for example: Node 0 is neighbors with Node 1 and vice versa. Node 0 will open up text file from0to1.txt and Node 1 will open up a textfile from1to0.txt.
I verify the creation of these files in this code:
for(Integer i: neighbors){
File file = new File("from" + myId + "to" + i + ".txt");
try{
boolean fileMade = file.createNewFile();
if(!fileMade){
System.err.println("Node " + myId + ": File could not be created.\n Please delete the files before trying again.");
System.exit(1);
}
/**
boolean fileMade = file.createNewFile();
while(!fileMade){
System.out.println("Node " + myId + ": File is already present.");
System.out.println("Node " + myId + ": Deleting file...");
file.delete();
System.out.println("Node " + myId + ": File deleted");
System.out.println("Node " + myId + ": Trying again...");
fileMade = file.createNewFile();
}
*/
System.out.println("Node " + myId + ": File " + file.getName() + " successfully created.");
}
catch(Exception e){
e.printStackTrace();
}
Once these files have been opened up, I am opening them to write into them.
Each node will be sensing data from these "channels" that are text files. When reading, I am opening up these text files with a RandomAccessFile. When I am writing, I am opening up these text files with a FileWriter/BufferedWriter.
The problem is that when I attempt to open up the text files for reading with a RandomAccessFile, it throws a FileNotFoundException. I have attempted to run f.exist() and it also turns up as false.
Why is it not creating the file/not acknowledging that the file exists?
Here is the code:
for(Integer n: neighbors){
RandomAccessFile raf = null;
File f = new File("from" + n + "to" + nodeID + ".txt");
System.out.println(f.exists());
System.out.println(f.canRead());
//FileReader fr = null;
try{
System.out.println("Trying to open file: " + "from" + n + "to" + nodeID + ".txt");
//System.out.println("Node " + nodeID + ": Setting up Random Access File");
//fr = new FileReader(new File("from" + n + "to" + nodeID + ".txt"));
//System.out.println(fr.read());
//fr.close();
raf = new RandomAccessFile(f, "r");
raf.seek(offsetList.get(n));
/**
I need to write 100 integers created randomly into a file using Java I/O
this is my code so far:
package lab;
import java.util.*;
import java.io.*;
public class test {
public static void main(String[] args) {
Random num = new Random();
try {
File file = new File("E:\\Test.txt");
if(file.exists()) {
file.createNewFile();
}
PrintWriter out = new PrintWriter(new File("E:\\Test.txt"));
for (int i = 0; i <= 9; i++){
output.print(num.nextInt(100)+" "+num.nextInt(100) + " " +
num.nextInt(100) + " " + num.nextInt(100) + " " + num.nextInt(100) + " "
+ num.nextInt(100) + " " + num.nextInt(100) + " " + num.nextInt(100) + " "
+ num.nextInt(100) + " " + num.nextInt(100));
output.println();
}
out.close();
Scanner input = new Scanner(file);
while(input.hasNext()) {
System.out.println(input.nextLine());
}
input.close();
}
catch (IOException ex) {
System.out.println("File Already Exists!");
}
}
}
I need to simplify the "for-loop", and be able to read back the file to display it.
Can anyone help?
First of all do not concatenate Strings in for loops (new objects are created), use StringBuilder.
Once you build your string with random numbers save it like this:
http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
StringBuilder str = new StringBuilder();
Random rng = new Random();
for (int i = 0; i < 100; ++i)
str.append(rng.nextInt(100) + " ");
System.out.println(str.toString());
Replace System.out.println(str.toString()); with your filestream writing.
File file = new File("File_name.txt");
StringBuilder str = new StringBuilder();
try (PrintWriter output = new PrintWriter(file);) {
for (int i = 0; i < 100; i++) {
int num = ((int)(Math.random() * 500) + 1);
output.print(num);
output.print(" ");
str.append(num + " ");
}
}
System.out.println(str.toString());
I am trying to get my if statements to have seperate write commands such as bw.write(b + " - " + a +" = " + c + newLine); the issue is due to the newLine string and the bw
Buffer being within curley braces I cannot get those to work. any ideas?
try {
File file = new File("src/written.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
String newLine = System.getProperty("line.separator");
bw.write(b + " - " + a +" = " + c + newLine);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
JOptionPane.showMessageDialog(null,"Amount Transfered: " + b + " - " + "Previous Balance: " + a +"\nRemaning Balance: " + c);
if( c == 0){
JOptionPane.showMessageDialog(null,"Transfered granted. Balance empty","Transation successful!",JOptionPane.WARNING_MESSAGE);
}else if (c > 0){
JOptionPane.showMessageDialog(null,"Transfered granted.","Transation successful!",JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(null,"Transfer denied due to insufficent funds.","Transaction denied!",JOptionPane.ERROR_MESSAGE);
}
I'm not entirely sure what your goal is, but it looks like you're losing the scope on your BufferedWriter bw.
If you want to use bw outside the { } it currently resides in, declare:
BufferedWriter bw;
try {
.....
bw = new BufferedWriter(fw);
}
That way, bw is declared before the try block, which lets you use it all throughout the rest of the code as well as within the try block.
Having a tiny issue where not sure how to call a specific function to print its details.
I created a Radio button that checks the Total physical Memory on a PC, also have one for GPU and both work just fine.
Now I am lost on how to call that same function so it prints in the bigger window when I do a system scan of specific system properties.
if (isWindows()) {
jTextArea1.setText(header + "User Name : " + name
+ "\nOperating System :" + jComboBox1.getSelectedItem()
+ "\nSelected Gamer Ability : " + this.jComboBox4.getSelectedItem()
+ "\nSelected Age Group :" + this.jComboBox5.getSelectedItem()
+ "\nSystem Version : " + System.getProperty("os.version")
+ "\nSystem Architecture : " + System.getProperty("os.arch")
PROBLEM PART + "\nSystem Total Ram : " + this.jRadioButton2......
+ "\nScan ID : " + n + "\n \n")
}
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String filepath = "..\\Checker\\src\\batchchecker\\memory.bat";
try
{
Process p = Runtime.getRuntime().exec(filepath); // filepath
p.waitFor();
InputStream in = p.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c = -1;
while ((c = in.read()) != -1)
{
baos.write(c);
}
String response = new String(baos.toByteArray());
jRadioButton2.setText(evt.getActionCommand());
JOptionPane.showMessageDialog(null, "" + evt.getActionCommand()
+ response);
}
catch (Exception e)
{
e.printStackTrace(System.err);
}
}
}
As you can see from above code, my radio does what it needs to and tested. I am just not sure how to call the same result into the bigger picture where it actual prints all the details along with the rest. The line of code is + "\nSystem Total Ram : " + this.jRadioButton2......
Seems like you just need to move your implementation to a separate method that can be called from both your actionPerformed() method and your other call. For example:
public String findMemoryDetails() {
// ... put code here
}
Then call it here:
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String memDetails = findMemoryDetails();
JOptionPane.showMessageDialog(null, "" + evt.getActionCommand() + memDetails);
}
And here:
+ "\nSystem Total Ram : " + findMemoryDetails()