Working with some legacy code, and encountered this:
File file = new File()
File[] files = file.listFiles();
for(int i=0;i<files.length;i++)
try {
{
System.out.println("Do stuff");
}
} catch (Exception e) {
e.printStackTrace();
}
it compiles and runs, but I don't know which loop is inside the other, or why it works.
This code
File file = new File();
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
try {
{
System.out.println("Do stuff");
}
} catch (Exception e) {
e.printStackTrace();
}
Is same as this one
File file = new File();
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
try {
{
System.out.println("Do stuff");
}
} catch (Exception e) {
e.printStackTrace();
}
}
And same as this one
File file = new File();
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
try {
System.out.println("Do stuff");
} catch (Exception e) {
e.printStackTrace();
}
}
Java allows you to have some "extra" brackets, but it does not change anything (well it change the scope of variables if you declare them inside it, but this is not the case)
try-catch isn't a loop, it's just a construct that executes the try block (once) and the possibly the catch block(s).
If you break it down, here's what's going on:
for each index i in the files array
do one thing, a try-catch
the try block itself has an "anonymous block" (the block created by the curlies inside the try -- it starts at the second curly brace after the word try)
the anonymous block has one statement, System.out.println("Do stuff");
the catch block prints the exception's stack trace (if an exception thrown, of course)
Related
This method shows only a name of file in console.
JTextArea area = new JTextArea(20,40);
public void readContent(){
KreatorPytan kp = new KreatorPytan();
File file = new File("D:\\IT\\JAVA\\zadanie\\Testy");
File[] files = file.listFiles();
for(int i = 0; i < files.length; i++){
try {
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(files[i]));
if(files[i].isFile()){
System.out.println(files[i].getName());
area.read(reader, "File");
}
} catch (FileNotFoundException ex) {
Logger.getLogger(WyborPytan.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(WyborPytan.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I don't know why these names of files are not saving to my jtextarea. Can you help me?
This code is reading files to JTextArea and rewriting each previous file contents with the next. So as result you will see the last file contents. If you want to get file names in JTextArea, you don't need to read file, just do smth like
for (int i = 0; i < files.length; i++) {
area.append(files[i].getName() + '\n');
}
The overarching theme of this project is to sort stuff. My full code works (sort of) but the issue is that it always sorts my data as a String and I am pretty sure its caused by that fact that I am reading the dataFile's line as a String and inputting that into the array as a string.
Object[] list = new Object[n];
if (n > 0) {
try {
BufferedReader file = new BufferedReader(new FileReader("dataFile.txt"));
for (int i = 0; i < list.length; i++) {
String t = file.readLine();
if (t != null)
list[i] = t;
}
file.close();
}
catch (FileNotFoundException e) {
System.out.println("Error accessing file.");
} catch (IOException io) {
System.out.println("There was an error reading from the file.");
}
}
If someone could point me in the correct direction on how to read a line and input it into an array as an Object, I would be grateful.
A Java String is an Object. (String extends Object)
So you can get an Object reference via assignment!
Perhaps, you can try adding content from your file to an Object array like below:-
Object[] list = new Object[n];
if (n > 0) {
try {
BufferedReader file = new BufferedReader(new FileReader("dataFile.txt"));
for (int i = 0; i < list.length; i++) {
String t = file.readLine();
Object obj = t;
if (obj != null)
list[i] = obj;
}
file.close();
}
catch (FileNotFoundException e) {
System.out.println("Error accessing file.");
} catch (IOException io) {
System.out.println("There was an error reading from the file.");
}
}
Why don't you use Java8 internal tools to ready text files:
public static Object[] readAllLinesFromFile(Path path) throws IOException {
return Files.lines(path).toArray(String[]::new);
}
Figured out the issue. This code fixes, thanks to the people who helped.
void dataType() {
for (int i = 0; i < list.length; i++) {
try {
checkINT = Integer.parseInt((String) list[i]);
list[i] = checkINT;
} catch (Exception eInt) {
try {
checkDBL = Double.parseDouble((String) list[i]);
list[i] = checkDBL;
} catch (Exception eDbl) {
// Then its a string.
}
}
}
}
I have a list of binary files that I need to read and then, store to a variable. Each file is a collection of a huge number of doubles. The files were saved with a C program with double type in C under linux. Now, I want to read all these files using Java. Is this the fastest approach you can achieve? In my PC it takes 24 seconds to read 10 files (1.5 Mb/files with 194,672 doubles/file) and store them into an array. I was thinking in using some type of buffer but I am not sure if I should leave some bytes from the begging...
int i;
int num_f = 10;
int num_d = 194672;
File folder = new File(route);
File[] listOfFiles = folder.listFiles();
float double_list[][] = new float[num_f][num_d];
for (int file = 0; file < listOfFiles.length; file++) {
if (listOfFiles[file].isFile()) {
try{
br = new DataInputStream(new FileInputStream(listOfFiles[file].getAbsolutePath()));
//We read all file
i = 0;
while(br.available() > 0) {
//I know that float != double but I don't think I will lose a huge precision
//as the double numbers stored are in a region [-5,5] and with this way I reduce
//the amount of memory needed. (float) is not cpu consuming (<1s).
double_list[file][i++] = (float) br.readDouble();
}
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
//Close file
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Finally, I could do it with the help of Andreas and this website (http://pulasthisupun.blogspot.com.es/2016/06/reading-and-writing-binary-files-in.html) (check there for other type formats!). For endianness, the default option is the BIG_ENDIAN code but with that I had nonsense things as infinity numbers. Nonetheless, with LITTLE_ENDIAN i'm getting the correct numbers! Still though I will have to do some test in the future just to be sure that I do not have to let some extra byte from the beginning...
BTW, time spent: 0.160048575s, not bad ;)
int i;
int num_f = 10;
int num_d = 194672;
File folder = new File(route);
File[] listOfFiles = folder.listFiles();
float double_list[][] = new float[num_f][num_d];
for (int file = 0; file < listOfFiles.length; file++) {
if (listOfFiles[file].isFile()) {
try{
fc = (FileChannel) Files.newByteChannel(Paths.get(listOfFiles[file].getAbsolutePath()), StandardOpenOption.READ);
byteBuffer = ByteBuffer.allocate((int)fc.size());
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
fc.read(byteBuffer);
byteBuffer.flip();
buffer = byteBuffer.asDoubleBuffer();
((DoubleBuffer)buffer).get(double_list[file]);
byteBuffer.clear();
fc.close();
}catch (Exception e){
e.printStackTrace();
}finally {
try {
//Close file
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Whenever I run this method, it produces an error saying that there is no line. The file (inv.txt) is a 1 on 25 lines, So 25 ones, each on a seperate line.
public class Inventory
{
File inventory = new File("Resources/inv.txt");
File db = new File("Resources/db.txt");
FileWriter write;
StringBuilder writethis;
public void addItem(int item, int slot)
{
int i = 1;
writethis = new StringBuilder();
Scanner scan;
try
{
scan = new Scanner(inventory);
if (scan.hasNextLine())
{
while (i < slot)
writethis.append(scan.nextLine()); // This is where it says the
// error is. For reference,
// slot is 2. It may somehow
// be making an infinite loop,
// but I don't know why it
// would.
scan.nextLine();
writethis.append(item);
while (i < 24)
writethis.append(scan.nextLine());
System.out.println(writethis.toString());
scan.close();
}
try
{
write = new FileWriter(inventory);
write.write(writethis.toString());
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
Could this be due to the fact that the instance variable i is never incremented?
I would also close the data streams in a finally block.
I have the following method to write an array to a text file. If a existing text file is given then it works fine but if a file that doesn't exist is given neither try-catch will run the code to restart the method. I'm not given any error or anything but the catch block won't run. I didn't think i would need to catch for an IOException but the code won't even run if i don't do that. So yea, anyone know how i can get this to work?
Edit: Forgot to mention the getInput method prompts the user for input.
private static void openFileWriter(String prompt, boolean append, int wordsperline, String[] story) {
try {
try {
save = new PrintWriter(new FileWriter(getInput(prompt), append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for (int x = 0; x <= story.length-1; x++) {
if (story[x] == null) {
} else {
if (wordsperline == 21) {
save.println(story[x]);
wordsperline = 0;
} else {
save.print(story[x]);
wordsperline++;
}
}
}
save.close();
} catch (FileNotFoundException e1) {
openFileWriter("File not found", append,wordsperline,story);
}
} catch (IOException e) {
// TODO Auto-generated catch block
openFileWriter("File not found", append,wordsperline,story);
}
}
If the File does not exist you cannot write to it, in your catch block you are trying to write the error to the File that doesn't exist. Also, I think you only need 1 catch block here, and note that one of the if statement blocks is empty.
try this:
try
{
save = new PrintWriter(new FileWriter(getInput(prompt), append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for(int x = 0; x <= story.length-1; x++)
{
if (story[x] == null)
{
}
else
{
if (wordsperline == 21)
{
save.println(story[x]);
wordsperline = 0;
}
else
{
save.print(story[x]);
wordsperline++;
}
}
}
save.close();
}
catch (FileNotFoundException e1)
{
System.err.println(e1.getMessage());
}
catch (IOException e)
{
System.err.println(e.getMessage());
}
See FileWriter javadoc.
Quoting from the constructor doc:
Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
If you pass it a filename that doesn't exist, but is a legal filename in a location where you have permission to write, it simply creates the file.
Your code in fact does reach the catch blocks if you pass it a directory (somewhat oddly, it catches a FileNotFoundException in this situation for me rather than the documented IOException).
To check if a file exists, see File javadoc
Try this version and send the stack trace when you get the exception:
public static List<String> splitByLength(String filename, int length) {
List<String> splitWords = new ArrayList<String>();
for (int i = 0; i < str.length(); i += length) {
splitWords
.add(str.substring(i, Math.min(str.length(), i + length)));
}
return splitWords;
}
private static void openFileWriter(String prompt, boolean append,
int wordsperline, String[] story) {
PrintWriter save = null;
try {
save = new PrintWriter(new FileWriter("c:\\test.txt", append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for (int x = 0; x <= story.length - 1; x++) {
if (story[x] != null) {
List<String> splitWords = splitByLength(story[x], 21);
for (String line : splitWords) {
save.println(line);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (save != null) {
save.close();
}
}
}