开发者

read int form a file in java

I have a *.txt file that it has data like this:

  1222 25 36 25 14 25 25 36 363 25 15
    1253 69 54 87 54 285
]±غ'Q­ہx¸'،2ذç12â· 'ئ‰؟¦خ&{3ع*U6هؤ­ر–¨ر،³ڑُ‌ں¢œغ)™پ÷ةtڑت†éYْ(زH5x¸2ش/¨#ژ‏ظœ,tx[Kh6”¨
rٹ±k'¨اqaيïذüـvqشQ­0H888/ ح‎lںR–>Kْ¹bف‘دô†)oŒىٹط.fNؤ8ک„ٌnpwَ§IMقJ™؟س5؛x.Zµ‎™7ˆے¨‌أئ°—لف):©¢چR¢سï¶J±@JœOْ‏5TMè§è9´«7 –دس54)ںشw>’âغ2›Zi@وûr&  طFو-dة ôƒ( œءxƒ§أh(¢ش‘»开发者_StackOverflow中文版إV¨پ~ؤF؟!]&´ye\جہ„°?ّ!Uج3ص­wyc†P`¬:
ِS…ةّEژœ Zشâku‍ X§Rٌ¦ص«{â‹YwOڈ48¹Wٌ“i¾َه#™²|(³bˆiتژ-»çJ¯‍صl¦ر“+ءC’µہڈ™،£ظ(2€j¤ًگdك(`اء—꯳[f‌

first 17 chars of that are integer and others are binary.

now i want to read first 17 chars. how can i read them?


This is something you can do with a java.io.Scanner:

File f = new File("yourtxt.txt");
Scanner s = new Scanner(f);
for (int i = 0; i < 17 && s.hasNextInt(); ++i)
{
    int inputInteger = s.nextInt();
    // Handle your int here...
}

EDIT: The exception that is thrown is probably because of bytes you don't need between the integers.

Maybe you can try to do something like this:

DataInputStream dis = new DataInputStream(new FileInputStream(yourFile));
String numbers = dis.readLine() + " " + dis.readLine();
numbers = numbers.trim().replaceAll(" +", " ");
String[] array = numbers.split(" ");
for (int i = 0; i < array.length; ++i)
{
    int inputInteger = Integer.parseInt(array[i]);
    // handle inputInteger here...
}


I check it and it works

public static void main(String[] args){

        File f = new File("my.txt");

        if(f.exists()){
            Scanner scanner = null;
            try {
                scanner = new Scanner(f);            
            int [] arrayInt = new int [17];
            int i = 0;
            while(scanner.hasNextInt()){
                arrayInt[i++] = scanner.nextInt();
            }

            for(int tailElement : arrayInt){
                System.out.println(tailElement);
            }
            } catch (FileNotFoundException e) {
                e.printStackTrace(); 
            }
        }else{
            System.out.println("File not found!");
        }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜