When I try to use FileReader、FileWriter to copy a plain text file, it trapped in a dead circle.That's confused me a lot. I'd appreciate it if someone can help me.
FileReader in = new FileReader("./src/io/copyFile/CopyFileTest01.java");
FileWriter out = new FileWriter("Copy1.java");
char[] chars = new char[1024 * 512]; // once max copy 1MB
When I try to copy file like the followed way,it's ok.
while (true) { // ok
int count = in.read(chars);
System.out.println("count = " + count);
if (count == -1) {
break;
}
out.write(chars, 0, count);
}
However, when I try use the other way, it will trap in the dead circle.
int readCount = 0;
while ((readCount = in.read(chars)) != -1) { // dead circle
System.out.println("readCount = " + readCount);
System.out.println(Arrays.toString(chars)); // bad
out.write(chars, 0, readCount); writing after reading
}
I can't find the reason, and it puzzleed me a lot. I'd appreciate it if someone can help me.
There is the complete code.
package io.copyFile;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
public class CopyFileTest02 {
public static void main(String[] args) {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("./src/io/copyFile/CopyFileTest01.java");
out = new FileWriter("Copy1.java");
char[] chars = new char[1024 * 512];
int readCount = 0;
while ((readCount = in.read(chars)) != -1) { // dead
System.out.println("readCount = " + readCount);
System.out.println(Arrays.toString(chars)); // bad
out.write(chars, 0, readCount);
}
// flush
out.flush();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
Ok. I found that when remove the followd bolck, this code can work well.However, when I added the followed block, it will never exit the loop.
System.out.println(Arrays.toString(chars));
When I added that Arrays.toString(chars), It will print ',' in console and never stop like the picture.
enter image description here
I asked this question earlier and I forgot to clarify what my question was so hopefully I'm actually clear this time.
I basically need help with sorting a bunch of records in a file based on their number using an algorithm like bubble sort.
I have a file with 5 records where each file consists of a number of integer type and name of 32 characters(each record size should be 36 bytes). I have to store the records into a file. **This is what I need help with:**Then sort the records based on the numbers associated with them, using a sorting algorithm like bubble sort. Another requirement is that when the program sorts the records, it shouldn't read all records in memory at once but move them in the file. For example, after the program reads the first two records, it may switch the records (because 72 > 56) and write them in the same position in the file.
We were provided with the classes to read/write and have random access to the file.
These are the records as they were provided:
72 James
56 Mark
87 John
30 Phillip
44 Andrew
I need to sort these names according to their respective numbers. My question is, what would be the best way to implement this sorting?
Here's the code for the writing class:
package test;
//write to a file
import java.io.*;
class FileWriteStreamTest {
public static void main (String[] args) {
FileWriteStreamTest f = new FileWriteStreamTest();
f.writeMyFile();
}
void writeMyFile() {
DataOutputStream dos = null;
String record = null;
int recCount = 0;
try {
File f = new File("mydata.txt");
if (!f.exists())
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
dos = new DataOutputStream(bos);
//store records into file
dos.writeBytes(72 + " James \n");
dos.writeBytes(56 + " Mark \n");
dos.writeBytes(87 + " John \n");
dos.writeBytes(30 + " Phillip \n");
dos.writeBytes(44 + " Andrew \n");
} catch (IOException e) {
System.out.println("Uh oh, got an IOException error!" + e.getMessage());
} finally {
// if the file opened okay, make sure we close it
if (dos != null) {
try { dos.close(); }
catch (IOException ioe) { }
}
}
}
}
Here's the code for the reading class:
package test;
//read from a file
import java.io.*;
public class FileReadStreamTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileReadStreamTest f = new FileReadStreamTest();
f.readMyFile();
}
void readMyFile() {
DataInputStream dis = null;
String record = null;
int recCount = 0;
try {
File f = new File("mydata.txt");
if (!f.exists()) {
System.out.println(f.getName() + " does not exist");
return;
}
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while ( (record=dis.readLine()) != null ) {
recCount++;
System.out.println(recCount + ": " + record);
}
} catch (IOException e) {
System.out.println("Uh oh, got an IOException error!" + e.getMessage());
} finally {
// if the file opened okay, make sure we close it
if (dis != null) {
try { dis.close(); }
catch (IOException ioe) { }
}
}
}
}
Here's the code for the random access class:
package test;
//read or write to any place in the file
import java.io.*;
class FileRandomAccessTest {
public static void main (String[] args) {
FileRandomAccessTest f = new FileRandomAccessTest();
f.readWriteMyFile();
}
void readWriteMyFile() {
RandomAccessFile raf = null;
String s = null;
try {
File f = new File("mydata.txt");
if (!f.exists()) // check if the file exists
f.createNewFile(); // create a new file
raf = new RandomAccessFile(f, "rw"); // open a file for random access with "r", "rw"
if (raf.length() > 7) {// the size of the file
raf.seek(7); // move the file pointer
System.out.println(raf.readLine()); // read a line from the file pointer
s = raf.readLine();
System.out.println(s);
raf.seek(raf.getFilePointer() - s.length()); // get the file pointer
raf.writeBytes("Test RamdomAccessFile\n"); // write bytes
}
} catch (IOException e) {
System.out.println("Uh oh, got an IOException error!" + e.getMessage());
} finally {
// if the file opened okay, make sure we close it
if (raf != null) {
try { raf.close(); } // close the file
catch (IOException ioe) { }
}
}
}
}
My current bubble sort implementation that needs to be adapted for this problem:
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Sort {
public static void bubbleSort(int[] num ) {
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag ) {
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < num.length -1; j++ ) {
if ( num[ j ] < num[j+1] ) {
temp = num[ j ]; //swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.txt"));
int [] numbers = new int [5];
int i = 0;
while(scanner.hasNextInt()){
numbers[i++] = scanner.nextInt();
}
bubbleSort(numbers);
System.out.println(Arrays.toString(numbers));
}
}
I've been trying to use bufferedreader several times but every time I get some form error. This is time it is "not a statement" and "; expected" also "catch without try". I keep getting errors at the line with the try(bufferedreader) line. Am I using this correct? I am just trying it out and not quite sure how it works. from the online resource I've been looking at my code looks fine. But when I run my own it gives me errors.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Problem2 {
public static void main(String [] args) {
if(args.length != 1){
System.out.println("Please enter a txt file");
}
else{
String s;
try (BufferedReader br = new BufferedReader(New FileReader(args[0]))) {
while ( (s = br.readLine()) != null) {
String[] words = s.split("[^a-zA-Z0-9]+");
for(int i = 0; i < words.length; i++){
//code
}
}
}
br.close();
}
catch (FileNotFoundException ex){
System.out.println(ex);
}
catch (IOException ex){
System.out.println(ex);
}
}
}
}
1) The errors are simple, firstly you're supposed to use new FileReader (with lowercase n) rather than New FileReader (with uppercase N).
2) you're closing the else block before attaching the catch handlers to the try block.
I have now corrected both issues and the code below should compile.
if(args.length != 1){
System.out.println("Please enter a txt file");
}
else{
String s;
try (BufferedReader br = new BufferedReader(new FileReader(args[0]))) {
while ( (s = br.readLine()) != null) {
String[] words = s.split("[^a-zA-Z0-9]+");
for(int i = 0; i < words.length; i++){
//code
}
}
br.close();
}catch (FileNotFoundException ex){
System.out.println(ex);
}
catch (IOException ex){
System.out.println(ex);
}
}
I'm trying to make a spell checker and going to open the words in .txt file in a linked list but hasNextLine() always returns false.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.Scanner;
public class backEnd {
String string;
String[] splitted;
public backEnd(String s){
string=s;
}
public void splitter(){
splitted =string.split(" ");
for (int x=0; x<splitted.length; x++){
System.out.println(splitted[x]);
}
}
public void spellChecker(){
Serializable data = new String[100];
LinkedList<String> l=new LinkedList<String>();
File f= new File("WordDict.txt");
if(!f.exists())
try {
f.createNewFile();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream Fis=new FileInputStream(f);
Scanner sc = new Scanner(Fis);
System.out.println("Check outside nextline");
this is the point where it should take words line by line from .txt file but it always breaks the loop.
while (sc.hasNextLine()){
System.out.println("Check in nextline");
data = sc.nextLine();
l.add( (String) data);
}
sc.close();
}
catch(FileNotFoundException fnf){
fnf.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
int x=0;
int y=0;
while(x<splitted.length){
while(y<l.size()){
if(l.get(y)==splitted[x]){
System.out.println("Matched.");
y++;
}`enter code here`
}
System.out.println("Wrong spelling of: "+splitted[x]);
x++;
}
}
}
The obvious reason seems to be that the file WordDict.txt doesn't exist,
so your code creates it, but it's empty, so it has no next line.
In this code, put a breakpoint on f.createNewFile():
File f= new File("WordDict.txt");
if(!f.exists())
try {
f.createNewFile();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream Fis=new FileInputStream(f);
Scanner sc = new Scanner(Fis);
System.out.println("Check outside nextline");
Another obvious reason can be that the file exists but it's empty.
Most probably your problem is the first one, and your confusion comes from your assumption of the execution directory. That is, the program is probably not executed where you think. To verify what, change WordDict.txt to absolute path.
sc.hasNextLine() returns true just because is a Empty file!!! Try to write something on it.
In addition your while loop is infinite and a not correct compair (string == string is wrong):
int x=0;
int y=0;
while(x<splitted.length){
while(y<l.size()){
if(l.get(y)==splitted[x]){
System.out.println("Matched.");
y++;
}`enter code here`
}
System.out.println("Wrong spelling of: "+splitted[x]);
x++;
}
This loop maybe should be something like this:
int x=0;
int y=0;
while(x<splitted.length){
while(y<l.size()){
if(l.get(y).equals(splitted[x])){
System.out.println("l.get("+ y +") is "+ l.get(y) +", splitted["+x+"] is "+ splitted[x]);
System.out.println("Matched.");
y++;
x++;
}else{
System.out.println("Wrong spelling of: "+splitted[x]);
y++;
}
}
}
Hi guys i have a text file in the following path C:/Users/Marc/Downloads/vector25 which contains comma-separated values in the following format
-6.08,70.93,-9.35,-86.09,-28.41,27.94,75.15,91.03,-84.21,97.84,
-51.53,77.95,88.37,26.14,-23.58,-18.4,-4.62,46.52,-19.47,17.54,
85.33,52.53,27.97,10.73,-5.82,
How would i read this text file and store those doubles in an array ?
I'm currently thinking of trying a buffered reader but so far the answer eludes me can anyone point me in the right direction ?
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class subvector {
public static void main(String[] args){
FileReader file = null;
try {
file = new FileReader("C:/Users/Marc/Downloads/vector25");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Double> list = new ArrayList<Double>();
int i=0;
try {
Scanner input = new Scanner(file);
while(input.hasNext())
{
list.add(input.nextDouble());
i++;
}
input.close();
}
catch(Exception e)
{
e.printStackTrace();
}
for(double k:list){
System.out.println(k);
}
}
You should use a delimeter
Scanner input = new Scanner(file);
input.useDelimeter(",");
Scanner.nextDouble() uses whitespace as the delimiter by default. Your input has commas as delimiter. You should use input.useDelimiter(",") to set commas as the delimiter before calling input.hasNext(). Then it should work as expected.
I think your code snippet will not for the specified data i.e. -6.08,70.93,-9.35,-86.09,-28.41,27.94,75.15,91.03,-84.21,97.84, -51.53,77.95,88.37,26.14,-23.58,-18.4,-4.62,46.52,-19.47,17.54, 85.33,52.53,27.97,10.73,-5.82,
But your program will work fine these type of data :
19.60
63.0
635.00
896.63
47.25
I have modified your program and tested with your data also. It's working as expected.
public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader("D:\\log4j\\vector25.txt");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Double> list = new ArrayList<Double>();
int i=0;
Double d= null;
try {
BufferedReader input = new BufferedReader(file);
String s=null;
while((s=input.readLine())!=null) {
StringTokenizer st = new StringTokenizer(s,",");
while(st.hasMoreTokens()) {
try {
d = Double.parseDouble(st.nextToken());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list.add(i, d);
}
}
input.close();
} catch(Exception e) {
e.printStackTrace();
}
for(double k:list) {
System.out.println(k);
}
}
Please review it and let me know if you update anything.
This is my first POST on stackoverflow.
Thanks, Prasad